Use this
UILabel *label = [[UILabel alloc] init];
label.text = @"myStringsdsdvsvdsdvsdvsdndbndbnbdnbdnbdnpopopoploplklioolnhbfghrmyString";
label.numberOfLines = 0;
label.frame = CGRectMake(0, 50, 320, 568);
[self.view addSubview:label];
label.frame = CGRectMake(0, 42, [self widthForLabel:label withText:label.text], [self height:label withText:label.text]);
label.backgroundColor = [UIColor redColor];
for Dynamic width
-(CGFloat)widthForLabel:(UILabel *)label withText:(NSString *)text
{
if (text.length > 0)
{
NSAttributedString *attributedText = [[NSAttributedString alloc] initWithString:text attributes:@{NSFontAttributeName:label.font}];
CGRect rect = [attributedText boundingRectWithSize:(CGSize){label.frame.size.width, CGFLOAT_MAX}
options:NSStringDrawingUsesLineFragmentOrigin
context:nil];
return ceil(rect.size.width);
}
return 0;
}
for dynamic height
-(CGFloat)height:(UILabel *)label withText:(NSString *)text
{
if (text.length > 0)
{
NSAttributedString *attributedText = [[NSAttributedString alloc] initWithString:text attributes:@{NSFontAttributeName:label.font}];
CGRect rect = [attributedText boundingRectWithSize:(CGSize){label.frame.size.width, CGFLOAT_MAX}
options:NSStringDrawingUsesLineFragmentOrigin
context:nil];
return ceil(rect.size.height);
}
return 0;
}
![enter image description here]()
here problem is you need to initialize label with some frame like this
label.frame = CGRectMake(0, 50, 320, 568);
now when you have added label to your view then calculate dynamic width and height of label and again set the frame.
Hope it will work.