iPhone - Adjust UILabel width according to the text

后端 未结 7 1593
天涯浪人
天涯浪人 2020-12-28 08:17

How can I adjust the label Width according to the text? If text length is small I want the label width small...If text length is small I want the label width according to th

7条回答
  •  醉话见心
    2020-12-28 08:53

    Try these options,

    UIFont *myFont = [UIFont boldSystemFontOfSize:15.0];
    // Get the width of a string ...
    CGSize size = [@"Some string here" sizeWithFont:myFont];
    
    // Get the width of a string when wrapping within a particular width
    NSString *mystring = @"some strings some string some strings...";
    CGSize size = [mystring sizeWithFont:myFont
                                  forWidth:150.0
                    lineBreakMode:UILineBreakModeWordWrap];
    

    You can also try with [label sizeToFit]; Using this method, you can set frame of two labels as,

    [firstLabel sizeToFit];
    [secondLabel sizeToFit];
    secondLabel.frame = CGRectMake(CGRectGetMaxX(firstLabel.frame), secondLabel.origin.y, secondLabel.frame.size.width, secondLabel.frame.size.height);
    

提交回复
热议问题