Auto Layout to dynamically size uilabel width

风格不统一 提交于 2019-11-28 15:52:19
  1. Create the 1 point horizontal space between the labels: Control-drag from label2 to label1. Choose Horizontal Spacing from the pop-up. Double click the constraint. Change the constant to 1.
  2. Give label1 a max width: Select label1. Go to the top menu bar, select Editor > Pin > Width. Double click the constraint. Change the relationship to <= and change the constant to the max width.
  3. Vertically align the labels: Select both labels. Go to the top menu bar, select Editor > Align > Vertical Centers.
  4. You still need to set constraints that define how your labels are positioned in their container view. I leave that up to you. I pinned label1 32 points from the left edge of the root view and 34 points from top layout guide.
  5. Update the frames of the labels so they reflect the above constraints: Go to the menu bar in the lower right-hand corner of the canvas. Tap the "Resolve Auto Layout Issues" Tie-Fighter button. Select "Update All Frames…" in the pop-up.

Note: Notice that I did not have to create constraints to make label1's width reflect its content size. The content sizing constraints are generated automatically.

Please refer below constraints to Set UIlabel and UIButton flexible width;

Abhishek Gupta

Please first get textSize with below code:

    CGSize  textSize = { 230.0, 10000.0 };

    CGSize size = [[NSString stringWithFormat:@"%@", yourLabelText] 
                   sizeWithFont:[UIFont systemFontOfSize:10]
                   constrainedToSize:textSize
                   lineBreakMode:NSLineBreakByWordWrapping]; 

then set your first label frame with this content size:

   UILabel *lblFirst = [[UILabel alloc] initWithFrame:CGRectMake(X, Y, W, size.height)];
   lblFirst.lineBreakMode = YES;
   lblFirst.lineBreakMode = NSLineBreakByWordWrapping;
   lblFirst.numberOfLines =size.height;
   lblFirst.backgroundColor = [UIColor clearColor];
   [self.view addSubview:lblFirst];

then second label Frame will be:

 UILabel *lblFirst = [[UILabel alloc] 
 initWithFrame:CGRectMake(lblFollowerName.frame.size.width + lblFollowerName.frame.origin.x, Y, W, H)];
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!