用autolayout设置相同水平位置上的两个view的问题
我在写一个自定义的
UITabelViewCell
的时候遇到了subview排列的问题。
自定义的cell如下图所示:
我想要的效果是:timeLabel的内容能完全显示,然后titleLabel右边距离timeLabel 10px,titleLabel的宽度根据以上约束自动确定。我的代码如下:
[self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:[timeLabel]-15-|" options:0 metrics:nil views:views]];
[self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:[timeLabel(>=40)]-15-|" options:0 metrics:nil views:views]];
[self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:[timeLabel(<=70)]-15-|" options:0 metrics:nil views:views]];
[self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:[titleLabel]-10-[timeLabel]" options:NSLayoutFormatAlignAllCenterY metrics:nil views:views]];
但看起来显然不靠谱啊,请问大家该怎样解决,谢谢。
gmkyoko
9 years, 7 months ago
Answers
手写的代码参考:
UIImageView *myImageView=[[UIImageView alloc]init];
myImageView.backgroundColor=[UIColor groupTableViewBackgroundColor];
[self.view addSubview:myImageView];
UILabel *titleLabel=[[UILabel alloc]init];
titleLabel.text=@"bababababbababababbababababbabababab";
[self.view addSubview:titleLabel];
UILabel *timeLabel=[[UILabel alloc]init];
timeLabel.text=@"昨天 23:58";//15小时前,前天
timeLabel.textAlignment=NSTextAlignmentRight;
[self.view addSubview:timeLabel];
[myImageView mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.equalTo(self.view.mas_top).offset(30);
make.leading.equalTo(self.view.mas_left).offset(10);
make.width.mas_equalTo(80);
make.height.mas_equalTo(80);
}];
[titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
make.leading.equalTo(myImageView.mas_trailing).offset(10);
make.top.equalTo(self.view.mas_top).offset(40);
make.height.mas_equalTo(30);
make.trailing.equalTo(timeLabel.mas_leading).offset(-10);
}];
[timeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
make.trailing.equalTo(self.view.mas_trailing).offset(-10);
make.top.equalTo(self.view.mas_top).offset(40);
make.height.mas_equalTo(30);
make.width.mas_greaterThanOrEqualTo(34);
make.width.mas_lessThanOrEqualTo(85);//timelabel宽度的最大最小值根据你的font来调整算出来
}];
storyboard自动布局直接拉线同样可以实现参考:
imgae约束
titlelabel约束
timelabel约束
detaillabel约束
高达08MS
answered 9 years, 7 months ago