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.
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;
