Add texfield in runtime in IOS - ios7

I want to make an "add" button to add as many textfields as i want in my scroll view.
I did this already
UITextField *text=[[UITextField alloc]initWithFrame:CGRectMake(50,50,200,200)];
[self.scrollView addSubview:text];
But is not working.
Thanks!

If this is your complete button code:
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button setTitle:#"Show View" forState:UIControlStateNormal];
button.frame = CGRectMake(80.0, 210.0, 160.0, 40.0);
// add this
[button addTarget:self action:#selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
// continue
[self.mainScroll addSubview:button];
Then add this somewhere:
- (void) buttonPressed:(UIButton *)button {
UITextField *text=[[UITextField alloc]initWithFrame:CGRectMake(50,50,200,200)];
text.backgroundColor = [UIColor greenColor]; // just to make sure it's showing up.
[self.scrollView addSubview:text];
}

First create common function like this,
-(void)setTextfieldStyle:(UITextField *)pTmpTextField
{
pTmpTextField.borderStyle = UITextBorderStyleRoundedRect;
pTmpTextField.font = [UIFont systemFontOfSize:15];
pTmpTextField.placeholder = #"First Name";
pTmpTextField.autocorrectionType = UITextAutocorrectionTypeNo;
pTmpTextField.keyboardType = UIKeyboardTypeDefault;
pTmpTextField.returnKeyType = UIReturnKeyDone;
pTmpTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
pTmpTextField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
pTmpTextField.delegate = self;
}
and use this for creating UITextFiled,
int y = 0;
for(int i=0;i < 5;i++)
{
UITextField *txtTemp=[[UITextField alloc]initWithFrame:CGRectMake(0, y, 300, 31)];
txtTemp.tag = i;
[self setTextfieldStyle:txtTemp];
[self.view addSubview:txtTemp];
[txtTemp release];
y+=36;
}
This is UITextField's delegate method,
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
NSLog(#"%#",textField.text);
}
Hope this works for you as this works for me. only keep this in mind that add the text fields to your scroll view.
In the example am adding them to my view!

Related

Button's Tag are same in TableView

I add view for header, here is my code:
-(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
UIView *view = [[UIView alloc] init];
view.layer.borderWidth = 0.5;
view.layer.borderColor = [UIColor colorWithRed:127.0/255.0 green:229.0/255.0 blue:232.0/255.0 alpha:1.0].CGColor;
view.backgroundColor = [UIColor clearColor];
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(30, 0, 150, 50)];
label.text = sectionArray[section];
label.backgroundColor = [UIColor clearColor];
label.textColor = [UIColor colorWithRed:0.0 green:122.0/255.0 blue:1.0 alpha:1.0];
button = [[UIButton alloc] initWithFrame:CGRectMake(self.myTableView.frame.size.width - 50, 15, 20, 20)];
[button setImage:[UIImage imageNamed:#"down"] forState:UIControlStateNormal];
button.tag = section;
[button addTarget:self action:#selector(extentFunction) forControlEvents:UIControlEventTouchUpInside];
[view addSubview:label];
[view addSubview:button];
return view;
}
-(void)extentFunction {
switch (button.tag) {
case 0:
NSLog(#"0");
break;
case 1:
NSLog(#"1");
break;
case 2:
NSLog(#"2");
break;
case 3:
NSLog(#"3");
break;
default:
break;
}
}
The question is: the button's tag is same of each header, not the section integer (ex: first header button's tag is 0; second header button's tag is 1)that I want.
What should I do?
As first look its clear issue of local & global variable.
You need to define your button as local variable and use button action sender as button object and get tag from that button.
Look at below code I think it will help you to understand your issue:
-(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
UIView *view = [[UIView alloc] init];
view.layer.borderWidth = 0.5;
view.layer.borderColor = [UIColor colorWithRed:127.0/255.0 green:229.0/255.0 blue:232.0/255.0 alpha:1.0].CGColor;
view.backgroundColor = [UIColor clearColor];
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(30, 0, 150, 50)];
label.text = sectionArray[section];
label.backgroundColor = [UIColor clearColor];
label.textColor = [UIColor colorWithRed:0.0 green:122.0/255.0 blue:1.0 alpha:1.0];
//Make Your Button local object not global
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(self.myTableView.frame.size.width - 50, 15, 20, 20)];
[button setImage:[UIImage imageNamed:#"down"] forState:UIControlStateNormal];
button.tag = section;
[button addTarget:self action:#selector(extentFunction) forControlEvents:UIControlEventTouchUpInside];
[view addSubview:label];
[view addSubview:button];
return view;
}
-(IBAction)btnClick:(UIButton*)sender{
switch (sender.tag) {
case 0:
NSLog(#"0");
break;
case 1:
NSLog(#"1");
break;
case 2:
NSLog(#"2");
break;
case 3:
NSLog(#"3");
break;
default:
break;
}
}
Let me know if its working fine.
This is your custom button code which is correct.
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(self.myTableView.frame.size.width - 50, 15, 20, 20)];
[button setImage:[UIImage imageNamed:#"down"] forState:UIControlStateNormal];
button.tag = section;
[button addTarget:self action:#selector(extentFunction) forControlEvents:UIControlEventTouchUpInside];
But you also need to add its sender and event to get the touch location of your button like below code.
[button addTarget:self action:#selector(extentFunction:event:) forControlEvents:UIControlEventTouchUpInside];
Now when you will click on button, extentFunction selector will get called. Now all you have to do is implement your button selector like below code.
-(void)extentFunction:(id)sender event:(id)event{
NSSet *touches = [event allTouches];
UITouch *touch = [touches anyObject];
CGPoint currentTouchPosition = [touch locationInView:_yourTableViewName];
NSIndexPath *indexPath = [_yourTableViewName indexPathForRowAtPoint: currentTouchPosition];
NSLog(#"%ld",indexPath.section);
}
Hope this will help you out.

Recognize a UIButton Tap inside a UIScrollView

I have a UIScrollView into which I add UIImageViews dynamically.
On the storyboard
After running the program
The code for adding an image is on my custom class. The class isn't assigned to any view:
- (id)initWithModel:(UIScrollView *)scroller page:(NSInteger)page image:(UIImage*)image{
self = [super init];
if (self) {
_scrollView = scroller;
_imageScrollIndex = page;
_image = image;
_frame = _scrollView.bounds;
_frame.origin.x = _frame.size.width * _imageScrollIndex;
_frame.origin.y = 0.0f;
_frame = CGRectInset(_frame, 10.0f, 0.0f);
_imageView = [[UIImageView alloc] initWithImage:_image];
_imageView.contentMode = UIViewContentModeScaleAspectFit;
_imageView.frame = _frame;
//adding delete image button
CGRect frame = _imageView.frame;
frame.origin.x = frame.size.width/2;
frame.origin.y = -frame.size.height/2+45;
//_imageView.userInteractionEnabled = YES;
UIButton *deleteImgButton = [[UIButton alloc] initWithFrame:frame];
deleteImgButton.userInteractionEnabled = YES;
[deleteImgButton addTarget:self action:#selector(clickedDeleteButton:)forControlEvents:UIControlEventTouchUpInside];
[deleteImgButton setImage:[UIImage imageNamed:#"close.png"] forState:UIControlStateNormal];
[_imageView addSubview:deleteImgButton];
////
[_scrollView addSubview:_imageView];
}
return self;
}
- (void)clickedDeleteButton:(UIButton*)button
{
printf("hi:\n");
}
I want to be:
Be able to recognize scroll event (Thus I think I need to keep the userinteractionenabled YES for the scrollView
Be able to recognize a tap on the delete button of the image
Any ideas how?
_scrl_ipad.contentSize = CGSizeMake(768,273 * temp);
_scrl_ipad.showsVerticalScrollIndicator=NO;
UIButton *btn_scrl=[UIButton buttonWithType:UIButtonTypeCustom];
[btn_scrl setFrame:CGRectMake(0,0, 328, 243)];
btn_scrl.tag=i-1;
[btn_scrl addTarget:self action:#selector(btn_scrl_tag:) forControlEvents:UIControlEventTouchUpInside];
[_scrl_ipad addSubview:btn_scrl];
-(IBAction)btn_scrl_tag:(id)sender
{
UIButton *btn = (UIButton *)sender;
NSLog(#"%d",btn.tag);
}

Two lines of text on UIButton with different fonts each

I found a way to add two lines of text on a UIButton,
but what I want is that each of these lines of texts
have different font (for instance one is bold, other not).
How is it possible to do this?
Thanks.
You should add 2 UILabel to the UIButton as subviews.
You can do it like:
UIButton *testButton = [UIButton buttonWithType:UIButtonTypeCustom];
testButton.frame = CGRectMake(0, 0, 200, 40);
[self.view addSubview:testButton];
UILabel *firstLineTestButton = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 20)];
firstLineTestButton.text = #"First line";
firstLineTestButton.font = [UIFont systemFontOfSize:12];
[testButton addSubview:firstLineTestButton];
UILabel *secondLineTestButton = [[UILabel alloc] initWithFrame:CGRectMake(0, 20, 200, 20)];
secondLineTestButton.text = #"Second line";
secondLineTestButton.font = [UIFont boldSystemFontOfSize:12];
[testButton addSubview:secondLineTestButton];
To also make highlighting possible for the UILabels, you need to make the highlighting of the button custom.
So add the actions to the button and then check the button subviews for the labels and change their colors.
[testButton addTarget:self action:#selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
[testButton addTarget:self action:#selector(changeColor:) forControlEvents:UIControlEventTouchDown];
[testButton addTarget:self action:#selector(touchCancel:) forControlEvents:UIControlEventTouchDragExit];
-(void)buttonAction:(UIButton*)sender
{
[self touchCancel:sender];
/* DO SOME MORE ACTIONS */
}
-(void)changeColor:(UIButton*)sender
{
sender.backgroundColor = [UIColor grayColor];
for( UIView *subview in sender.subviews ){
if( [subview isKindOfClass:[UILabel class]] ){
UILabel *subViewLabel = (UILabel*)subview;
subViewLabel.textColor = [UIColor blueColor];
}
}
}
-(void)touchCancel:(UIButton*)sender
{
sender.backgroundColor = [UIColor clearColor];
for( UIView *subview in sender.subviews ){
if( [subview isKindOfClass:[UILabel class]] ){
UILabel *subViewLabel = (UILabel*)subview;
subViewLabel.textColor = [UIColor blackColor];
}
}
}
The solution of Roland is good, another way to do this would be to use a NSAttributedString. The downside is, that it only works in iOS 6 and above.
If this is not a problem, here is the code
- (void)viewDidLoad
{
[super viewDidLoad];
// We want 2 lines for our buttons' title label
[[self.button titleLabel] setNumberOfLines:2];
// Setup the string
NSMutableAttributedString *titleText = [[NSMutableAttributedString alloc] initWithString:#"This should be bold,\n and this should not."];
// Set the font to bold from the beginning of the string to the ","
[titleText addAttributes:[NSDictionary dictionaryWithObject:[UIFont boldSystemFontOfSize:14] forKey:NSFontAttributeName] range:NSMakeRange(0, 20)];
// Normal font for the rest of the text
[titleText addAttributes:[NSDictionary dictionaryWithObject:[UIFont systemFontOfSize:14] forKey:NSFontAttributeName] range:NSMakeRange(20, 22)];
// Set the attributed string as the buttons' title text
[self.button setAttributedTitle:titleText forState:UIControlStateNormal];
}
You can add two UILabels as subview of the button and then can set the text of the labels as
[lbl1 setFont:[UIFont fontWithName:#"Arial-Bold" size:18]];
[lbl2 setFont:[UIFont fontWithName:#"Arial" size:16]];
For proper animation, you should subclass UIButton and redraw it when its state changes.
(void)drawRect:(CGRect)rect
{
if (!self.firstLineTestButton) {
self.firstLineTestButton = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 20)];
self.firstLineTestButton.text = #"First line";
self.firstLineTestButton.font = [UIFont systemFontOfSize:12];
[self addSubview:self.firstLineTestButton];
}
if (!self.secondLineTestButton) {
self.secondLineTestButton = [[UILabel alloc] initWithFrame:CGRectMake(0, 20, 200, 20)];
self.secondLineTestButton.text = #"Second line";
self.secondLineTestButton.font = [UIFont boldSystemFontOfSize:12];
[self addSubview:self.secondLineTestButton];
}
if (!self.highlighted) {
// Do custom drawing such as changing text color
} else {
// Do custom drawing such as changing text color
}
}
(void)setHighlighted:(BOOL)highlighted {
[super setHighlighted:highlighted];
// Force redraw of button
[self setNeedsDisplay];
}

iOS edit UIButton properties

I am working on the basics of iOS development.
So far I have a button that on press, will show some text. But what I want to do is after it is pressed, I want it to then change the text of the button, so far this is what I have:
- (void)viewDidLoad
{
[super viewDidLoad];
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
//button.backgroundColor = [UIColor redColor];
button.titleLabel.textColor=[UIColor blackColor];
button.frame = CGRectMake(25, 100, 275, 60);
[button setTitle:#"Press this button to reveal the text!" forState:UIControlStateNormal];
[button addTarget:self action:#selector(button_method:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)button_method:(UIButton *)sender {
NSString *test = #"I am learning Objective-C for the very first time! Also, this is my first ever variable!";
// handle button press
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(25, 25, 275, 60)];
label.text = test;
label.numberOfLines = 0;
label.lineBreakMode = UILineBreakModeWordWrap;
//label.lineBreakMode = NSLineBreakByWordWrapping; //iOS 6 only
[self.view addSubview:label];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
When I try adding [button setTitle:#"You pressed the button"]; to button_method
This doesn't work... why? And how would I make it work?
When I try adding [button setTitle:#"You pressed the button"]; to button_method, it doesn't work... why?
Because that method is nonexistent on UIButton.
And how would I make it work?
By using a method that UIButton actually responds to. For example:
[sender setTitle:#"You pressed the button" forState:UIControlStateNormal];
And read the relevant documentation, please.
Your code will not change the title of the button. But simply add a label as a subview for your view. Is this what you want?
If you want to change the text on the button you will want to do sender.title.text = test; in your button_method
I also recommend adding a NSLog(#"Button pressed"); to your button press method to double check that it is being called.

UIbutton with longpress and Touchup inside

How to create a UIButton With two actions.
I know by using UILongPressGestureRecognizer we can perform Longpress.
But my requirement is,When I Long Press UIButton,it has to perform one action and when touch
up inside it, it has to perform another action.
Thanks.
Below is my code.
UIImage *redImage = [UIImage imageNamed:#"TabFav2.png"];
tabRedbutton = [UIButton buttonWithType:UIButtonTypeCustom];
[tabRedbutton setImage:redImage forState:UIControlStateNormal];
tabRedbutton.frame = CGRectMake(0.0, 0.0, 50,35);
redTAb = [[UIBarButtonItem alloc] initWithCustomView:tabRedbutton];
[tabRedbutton addTarget:self action:#selector(redbottonmethod) forControlEvents:UIControlEventTouchUpInside];
longpressGesture1 = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:#selector(longPressHandler:)];
longpressGesture1.minimumPressDuration =0.1;
[longpressGesture1 setDelegate:self];
longpressGesture1.cancelsTouchesInView = NO;
[tabRedbutton addGestureRecognizer:longpressGesture1];
[longpressGesture1 release];
- (void)longPressHandler:(UILongPressGestureRecognizer *)gestureRecognizer {
if (longpressGesture.state == UIGestureRecognizerStateBegan)
{
NSlog(#"Long press");
}
}
-(void)redbottonmethod
{
NSlog(#"single tapped");
}
For the tap you can use UIButton's "addTarget:..." method and for the longpress you can add a gesture recognizer:
UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
btn.frame = CGRectMake(100.0, 100.0, 100.0, 20.0);
[btn setTitle:#"Test" forState:UIControlStateNormal];
[btn addTarget:self action:#selector(userTapped:) forControlEvents:UIControlEventTouchUpInside];
UILongPressGestureRecognizer *gr = [[UILongPressGestureRecognizer alloc] init];
[gr addTarget:self action:#selector(userLongPressed:)];
[btn addGestureRecognizer:gr];
[gr release];
[self.view addSubview:btn];
Of course you need to implement the 2 methods that will be called:
- (void)userTapped:(id)sender {
NSLog(#"user tapped");
}
- (void)userLongPressed:(id)sender {
NSLog(#"user long pressed");
}
Hope that helps.
=========
EDIT: It seems that you are using your button as a BarButtonItem inside a UIToolbar. So I changed my code to do the same:
- (void)viewDidLoad {
[super viewDidLoad];
// set up the button
UIImage *redImage = [UIImage imageNamed:#"TabFav2.png"];
UIButton *tabRedbutton = [UIButton buttonWithType:UIButtonTypeCustom];
tabRedbutton.backgroundColor = [UIColor redColor];
[tabRedbutton setImage:redImage forState:UIControlStateNormal];
tabRedbutton.frame = CGRectMake(0.0, 0.0, 50,35);
// set up a bar button item with the button as its view
UIBarButtonItem *redTab = [[UIBarButtonItem alloc] initWithCustomView:tabRedbutton];
// set up toolbar and add the button as a bar button item
UIToolbar *toolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0.0, 100.0, 768.0, 40.0)];
toolbar.barStyle = UIBarStyleBlack;
NSArray *items = [NSArray arrayWithObject:redTab];
[toolbar setItems:items];
[self.view addSubview:toolbar];
[toolbar release];
// add tap handler to button for tap
[tabRedbutton addTarget:self action:#selector(redbottonmethod) forControlEvents:UIControlEventTouchUpInside];
// add gesture recognizer to button for longpress
UILongPressGestureRecognizer *longpressGesture1 = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:#selector(longPressHandler:)];
longpressGesture1.minimumPressDuration =0.1;
[tabRedbutton addGestureRecognizer:longpressGesture1];
[longpressGesture1 release];
}
And the two methods that get called:
- (void)longPressHandler:(UILongPressGestureRecognizer *)gestureRecognizer {
NSLog(#"Long press");
}
-(void)redbottonmethod {
NSLog(#"single tapped");
}
This code definitely works.
By the way: I noticed that in your code in the 2 methods that get called you have typo: You must use NSLog() and not NSlog(). Could that be the problem?