首页 > 代码库 > ios-UILabel居中随内容自适应,后面的控件跟在其后
ios-UILabel居中随内容自适应,后面的控件跟在其后
如图绿蓝框所示,UILabel显示名字,Label框随名字长短而自适应,后面的性别图片跟在其后显示
分两部分:第一部分先布局
//名字
self.nameLab = [[UILabel alloc]initWithFrame:CGRectMake(0, 200, SCREEN_WIDTH, 20)];
self.nameLab.textColor = [UIColor whiteColor];
self.nameLab.font = [UIFont fontWithName:@"Helvetica-Blod" size:19];
self.nameLab.textAlignment = NSTextAlignmentCenter;
self.nameLab.backgroundColor = [UIColor clearColor];
[self.bgV addSubview:self.nameLab];
//性别
self.sexImageView = [[EGOImageView alloc]init];
[self.bgV addSubview:self.sexImageView];
第二部分解析得到数据后,根据内容自适应宽度,再重设性别图片的位置
self.nameLab.text = self.memberNmStr;//名字
[self.nameLab sizeToFit];
CGSize size = [self.nameLab.text sizeWithFont:[UIFont systemFontOfSize:19] constrainedToSize:CGSizeMake(SCREEN_WIDTH, 20) lineBreakMode:NSLineBreakByWordWrapping];
CGRect r1 = self.nameLab.frame;
r1.size.width = size.width;
self.nameLab.frame = r1;
self.nameLab.center = CGPointMake(self.bgV.frame.size.width/2, 130+10);
[self.sexImageView setFrame:CGRectMake(self.nameLab.frame.size.width + self.nameLab.frame.size.width + 10, 130, 20, 20)];
CGRect r2 = self.sexImageView.frame;
r2.origin.x = self.nameLab.frame.origin.x + 10 + self.nameLab.frame.size.width;
self.sexImageView.frame = r2;
ios-UILabel居中随内容自适应,后面的控件跟在其后