I want create UIButton from NSString.
I have one string like this #"First Button" I want first get size of width pixel and after create one Button According to this string but I don't know about it.
please guide me.
You can get the CGSize of NSString using sizeWithAttributes (before we used sizeWithFont but this is now deprecated method with iOS 7) and then create UIButton according to the size like
NSString *string = #"First Button";
CGSize size = [string sizeWithAttributes:
#{NSFontAttributeName:
[UIFont systemFontOfSize:27.0f]}];
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(0, 50, size.width, size.height);
button.titleLabel.textColor = [UIColor blackColor];
[button setTitle:string forState:UIControlStateNormal];
button.backgroundColor = [UIColor redColor];
[self.view addSubview:button];
Review this working fine for me.
Hope this will help you.
First you have to get the size of the text by using
NSString someText = #"some Text";
CGSize constraintSize = CGSizeMake(youMaxWidthForButton, youMaxHeightForButton);
CGRect labelSize = [someText boundingRectWithSize:constraintSize options:NSStringDrawingUsesLineFragmentOrigin attributes:#{NSFontAttributeName:[UIFont systemFontOfSize:17.0f]} context:nil];
than you create your UIButton
UIButton *button = [[UIButton alloc]initWithFrame:labelSize];
finally you set the button title
button.titleLabel.text = someText;
Related
I used a for loop to create several images and sliders on a scroller, how can I change the alpha of the images by changing the value of sliders? here is my code
I've tried to declare the uiimages outside the function loadImages, but I dont think this is a good idea.
I know how to do it without using for loop, but if I want to use for loop, how can I let the function know which uiimage it should operate on. Cause all the uiimages created in the for loop are not public objects I think.
-(void)loadImages
{
for (int i = 0; i < 10; i++){
//show drawing position in the output
NSLog(#"x:%i, y:%i",xInc, yInc);
//text label on the slider button
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(78 + xInc, 55+yInc, 200, 20)];
Person *thisPerson = [arrayOfPerson objectAtIndex:i];
NSString *namePerson = thisPerson.name;
[label setText:[NSString stringWithFormat:#"%#",namePerson]];
[label setTextColor:[UIColor whiteColor]];
[label setBackgroundColor:[UIColor clearColor]];
label.textAlignment = NSTextAlignmentCenter;
//front office background image of slider
NSString *frontimageName = [NSString stringWithFormat:#"frontofficeBUTTON.png"];
UIImageView *frontimgView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:frontimageName]];
frontimgView.frame = CGRectMake(xInc, 10 + yInc, 332, 70);
[frontimgView setTag:i];
//back office background image of slider
NSString *backimageName = [NSString stringWithFormat:#"backofficeBUTTON.png"];
UIImageView *backimgView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:backimageName]];
backimgView.frame = CGRectMake(xInc, 10 + yInc, 332, 70);
[backimgView setTag:i];
//slider
UISlider *slider=[[UISlider alloc] initWithFrame:CGRectMake(5+ xInc, 25+yInc, 322, 40)];
//give a id tag to the slider
[slider setTag:i];
//set a action to the slider
[slider addTarget:self action:#selector(UnlocklinkSlider:) forControlEvents:UIControlEventTouchUpInside];
//define the appearance of the slider
UIImage *stetchLeftTrack= [[UIImage imageNamed:#"Nothing.png"]
stretchableImageWithLeftCapWidth:30.0 topCapHeight:0.0];
UIImage *stetchRightTrack= [[UIImage imageNamed:#"Nothing.png"]
stretchableImageWithLeftCapWidth:30.0 topCapHeight:0.0];
[slider setThumbImage: [UIImage imageNamed:#"rightBUTTON.png"] forState:UIControlStateNormal];
[slider setMinimumTrackImage:stetchLeftTrack forState:UIControlStateNormal];
[slider setMaximumTrackImage:stetchRightTrack forState:UIControlStateNormal];
yInc = yInc + 80;
[_scrollView addSubview:backimgView];
[_scrollView addSubview:frontimgView];
[_scrollView addSubview:label];
[_scrollView addSubview:slider];
}
[_scrollView setContentSize:CGSizeMake(320, scrollLength)];
}
- (void)UnlocklinkSlider:(UISlider*)slider
{...}
Your slider should have a target and action added for UIControlEventValueChanged so that the image updates in sync (though it will work on touch up too). When you get the callback, use the slider tag to find the image view with the matching tag. Then set the image view alpha to slider.value.
To find the image view, you could loop over the subviews of the scroll view and check the tags of the subviews. You will want to change the tags from your current code as you have lots of things with the same tags.
A better option is to store references to the image views in an array property on your controller, then use the slider tag as the index in that array.
I'm doing surveys like project in which questions and answers are displayed. I'm displaying them in tableView with labels and buttons. But Now I am not getting how to handle each answer selected.
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSMutableArray *sectionItems=[self.finalarray objectAtIndex:indexPath.section];
int n=[sectionItems count];
NSString *question = [NSString stringWithFormat:#"%#",[[sectionItems objectAtIndex:indexPath.row] objectForKey:#"Question"]];
CGSize constraint1 = CGSizeMake(320, 2000.0f);
CGSize size1 = [question sizeWithFont: [UIFont fontWithName:#"Helvetica-Bold" size:14] constrainedToSize:constraint1 lineBreakMode:NSLineBreakByWordWrapping];
lblQuestion = (UILabel *)[hlcell viewWithTag:1];
lblQuestion.text = [NSString stringWithFormat:#"%#",question];
lblQuestion. numberOfLines=0;
lblQuestion.frame = CGRectMake(10,15, size1.width, size1.height);
UIButton *btTemp1 = [[UIButton alloc]initWithFrame:CGRectMake(10, lblQuestion.frame.origin.y+lblQuestion.frame.size.height,10, 15)];
[btTemp1 addTarget:self action:#selector(radioButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
btTemp1.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
[btTemp1 setImage:[UIImage imageNamed:#"radio_button_off.png"] forState:UIControlStateNormal];
[btTemp1 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
btTemp1.titleLabel.font =[UIFont systemFontOfSize:14.f];
[hlcell.contentView addSubview:btTemp1];
NSLog(#"%#",[[sectionItems objectAtIndex:1] objectForKey:#"Description"]);
NSString *option1 = [NSString stringWithFormat:#"%#",[[sectionItems objectAtIndex:1] objectForKey:#"Description"]];
CGSize constraint2 = CGSizeMake(320, 2000.0f);
CGSize size2 = [option1 sizeWithFont: [UIFont fontWithName:#"Helvetica-Bold" size:14] constrainedToSize:constraint2 lineBreakMode:NSLineBreakByWordWrapping];
lblOption1 = (UILabel *)[hlcell viewWithTag:1];
lblOption1.text = [NSString stringWithFormat:#"%#",option1];
[lblOption1 setNumberOfLines:0];
lblOption1.frame = CGRectMake(30,lblQuestion.frame.origin.y+lblQuestion.frame.size.height, size2.width, size2.height);
[hlcell.contentView addSubview:lblanswers];
UIButton *btTemp2 = [[UIButton alloc]initWithFrame:CGRectMake(10, lblOption1.frame.origin.y+lblOption1.frame.size.height,10, 15)];
[btTemp2 addTarget:self action:#selector(radioButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
btTemp2.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
[btTemp2 setImage:[UIImage imageNamed:#"radio_button_off.png"] forState:UIControlStateNormal];
[btTemp2 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
btTemp2.titleLabel.font =[UIFont systemFontOfSize:14.f];
[hlcell.contentView addSubview:btTemp2];
NSString *option2 = [NSString stringWithFormat:#"%#",[[sectionItems objectAtIndex:2] objectForKey:#"Description"]];
CGSize constraint3 = CGSizeMake(320, 2000.0f);
CGSize size3 = [option2 sizeWithFont: [UIFont fontWithName:#"Helvetica-Bold" size:14] constrainedToSize:constraint3 lineBreakMode:NSLineBreakByWordWrapping];
lblOption2 = (UILabel *)[hlcell viewWithTag:2];
lblOption2.text = [NSString stringWithFormat:#"%#",option2];
[lblOption2 setNumberOfLines:0];
lblOption2.frame = CGRectMake(30,lblOption1.frame.origin.y+lblOption1.frame.size.height, size3.width, size3.height);
[hlcell.contentView addSubview:lblOption2];
return hlcell;
}
I have 10 questions and how can I get the answer selected in each section and store it.
I am unable to refer indexpath. Section in radioButtonClicked method. And if I select a radiobutton in one section it is enabled and others are disabled. But if I check radiobutton in other section all the radiobuttons prevoiusly checked are also disabled. How can I handle radiobutton selection for a section separately.
Store clicked indexPath in a dictionary and manage cell display according to selected values. By setting them selected while creating them in cellForRowAtIndexPath, according to stored values. Like:
if([[selectedRows valueForKey:stringRepresentationOfIndexPath] boolValue] == YES)
[btTemp1 setSelected:YES];
Edit: selectedRows is dictionary that contains data of rows that are selected, update it in didSelectRowAtIndexPath, or on but click (if you are doing it like that).
I'm having a little problem with a UIButton I try to create programmatically. The problem is that the button shows up (i.e. if I set a background color, I can clearly see the button) and is clickable, but the title label isn't visible.
Here's what I'm doing :
valueButton = [UIButton buttonWithType:UIButtonTypeCustom];
[valueButton addTarget:self action:#selector(openList:) forControlEvents:UIControlEventTouchUpInside];
valueButton.frame = CGRectMake(160.0, decalageLabel+6.0, 120.0, 20.0);
[valueButton.titleLabel setTextAlignment:UITextAlignmentRight];
[valueButton.titleLabel setFont:[UIFont fontWithName:#"Helvetica-Neue-Light" size:17.0]];
UIColor * colorLabelValue = [[UIColor alloc] initWithRed:131.0/255.0 green:159.0/255.0 blue:86.0/255.0 alpha:1.0] ;
[valueButton setTitleColor:colorLabelValue forState:UIControlStateNormal];
if(txtValueField == NULL){
txtValueField = #"";
}
valueButton.titleLabel.text = [NSString stringWithFormat:#"%#", txtValueField];
NSLog(#"button : %# ", valueButton.titleLabel.text);
[self.contentView addSubview:valueButton];
Oh and I've made sure the title had an actual value, by NSLogging its text value, which works fine. So I don't know what's happening. Any idea?
Don't use [[button titleLabel] setTitle:] for this. Use [button setTitle:#"blah" forControlState:UIControlStateNormal].
This allows you to set a different title for highlighted, selected, up, etc.
Hi I have problem for set multiple lines to my Button which is declared like that:
button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.titleLabel.font = [UIFont systemFontOfSize: 12];
button.titleLabel.lineBreakMode = UILineBreakModeWordWrap;
button.titleLabel.numberOfLines = 0;
button.titleLabel.shadowOffset = CGSizeMake (1.0, 0.0);
[button addTarget:self
action:#selector(myButtonClick)
forControlEvents:UIControlEventTouchDown];
button.frame = CGRectMake(0.0, 100.0, 317.0, 100.0);
[button setTitle:string forState:UIControlStateNormal];
button.titleLabel.font = [UIFont systemFontOfSize: 12];
button.titleLabel.text = #"ahoj";
NSMutableString *ObratString = [[NSMutableString alloc] initWithString:button.titleLabel.text];
[ObratString appendString:#"\n"];
[ObratString appendString:#"caw"];
[ObratString appendString:#"\n"];
[ObratString appendString:#"helllo"];
button.titleLabel.text = ObratString;
[ObratString release];
[self.view addSubview:button];
But in the end I just see the first line.
Is there any way to make it work?
The UIButton displays it's text with a contained UILabel. The default for the contained label is to display one line of text only. This label is accessible through the titleLabel property, and anything you can do to a normal label can be done to it.
For example making it multi-lines broken by words:
ObjC:
myButton.titleLabel.numberOfLines = 0; // Dynamic number of lines
myButton.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
Swift:
myButton.titleLabel?.numberOfLines = 0; // Dynamic number of lines
myButton.titleLabel?.lineBreakMode = .byWordWrapping;
Swift version for the checked response:
myButton.titleLabel?.numberOfLines = 0
myButton.titleLabel?.lineBreakMode = NSLineBreakMode.ByWordWrapping
I created a grid of buttons. The following code creates the buttons and displays them, but there is no text on the button. Is there a setting I am missing? (Obj-C replies are fine, I'm bi-lingual)
RectangleF frame = new RectangleF (X + 3, Y + 3, cellWidth - 2, cellHeight - 2);
UIButton button = new UIButton (frame);
button.TitleLabel.Text = "Baha'i";
button.TitleLabel.Font = UIFont.FromName ("Helvetica-Bold", 15);
button.TitleLabel.TextColor = UIColor.Black;
button.TitleLabel.Frame = frame;
button.BackgroundColor = UIColor.FromWhiteAlpha(.5f,.5f);
this.AddSubview (button);
I think you want setTitle: forState:
[button setTitle:#"Baha'i" forState:UIControlStateNormal]
A UIButton inherits from UIView, so another way to add text and images, is to add subview. Example:
// My Image
UIImage *buttonImage = [UIImage imageNamed:#"myImage.png"];
UIImageView *buttonImageView = [[[UIImageView alloc]
initWithFrame:CGRectMake(0, 0,
buttonImage.size.width,buttonImage.size.height)] autorelease];
[buttonImageView setImage:buttonImage];
// My Label
UILabel* titleLabel = [[[UILabel alloc]
initWithFrame:CGRectMake(0, 0,
buttonImage.size.width, buttonImage.size.height)] autorelease];
titleLabel.text = #"My Text";
titleLabel.font = [UIFont fontWithName:#"Helvetica-Bold" size: 11.0];
titleLabel.textColor = [UIColor blackColor];
titleLabel.backgroundColor = [UIColor clearColor];
titleLabel.textAlignment = UITextAlignmentCenter;
// Create Button with Image and Label
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button addSubview:buttonImageView];
[button addSubview:titleLabel];
UIButton * selectCountryBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 100, 100)];
[selectCountryBtn setTitle:#"My Title" forState:UIControlStateNormal];
Here, I have create sample programmatically button, and then set the title for its Normal Control state, You can use your own button object for set the title string, additionally you can also set title text for another control states by change UIControlStateNormal to another required states.
In my case (Swift 4) it was the following:
btnLogin.setTitle("Welcome, " + var_name, for: [])
For swift Developers-
button.setTitle("Your button Name", for: .normal)
self.ButtonName.setTitle("Here Put Your variable model", for: .normal)
self.Button_name.titleLabel.text = #"Your title name";