How can I place a UILabel below an UIImageView such that it is always evenly placed

235 Views Asked by At

I have made a custom pop view which looks like this

I want to place the label of user name below the user image which is the rounded UIImageView in the given image

I want the user name to be placed evenly irrespective of the size of the text. Like I want the name to appear like this

enter image description here

3

There are 3 best solutions below

3
Bista On
  1. Align the Label content to Center.

  2. Set a constraint from label to Image View. Horizontally center label to Image View.

Align label horizontally to imageview

0
pkc456 On

As you are not using the storyboard, Below code will help you in setting the frame of label:-

UILabel *labelName;//This will be your label instance
CGFloat yAxis = 50;//This will be your image view's y axis + image view's height
[labelName setFrame:CGRectMake(0, yAxis, self.view.frame.size.width, self.view.frame.size.height)];
//Set the color/Font other properties of label as desired

[labelName setTextAlignment:NSTextAlignmentCenter];
0
Teja Nandamuri On

Setting the constraint is the efficient solution.

Either you can follow the storyboard way as suggested by Mr.UB or the approach it by code way.I suggest you to use Masonry for setting the constraints if you wish to proceed by code.

And you can simply do:

[your-label mas_makeConstraints:^(MASConstraintMaker *make) {
    make.top.equalTo(imgView.mas_top); //with is an optional semantic filler
    make.mas_centerX.equalTo(imgView.mas_centerX);
}];