0

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.

user3599133
  • 155
  • 3
  • 17

2 Answers2

2

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.

Buntylm
  • 7,345
  • 1
  • 31
  • 51
1

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;
Argent
  • 390
  • 1
  • 3
  • 11
  • my friend what is constraintSize? – user3599133 May 18 '14 at 05:05
  • this is the max value for width and height. For example you dont want your button to be bigger than your iphones width in portrait mode.. then you use `320` for the max width – Argent May 18 '14 at 05:10