【发布时间】:2018-06-18 16:13:55
【问题描述】:
我的代码中有两个类,一个是NameCell,它包含一个带有文本的简单UILabel。第二个是NameValueCell,它继承自该类,但还添加了属性UIView *valueView。
需要更改一个布局约束。我正在寻找一种方法来覆盖:
H:|[nameView]| - nameView 应该占据NameCell 的全宽
与
H:|[nameView][valueView(==nameView)]| - nameView 与 valueView 的宽度比应为 NameValueCell 中的 1:1
重写 NSLayoutConstraint 的最佳实践是什么?我必须在我的代码中坚持继承,因为我的应用程序需要许多不同的 UITableViewCell 特化。
NameCell.h:
@interface NameCell : UITableViewCell
@property (nonatomic, retain) IBOutlet UIView *nameView;
@property (nonatomic, retain) IBOutlet UILabel *nameLabel;
@end
NameValueCell.h:
@interface NameValueCell : NameCell
@property (nonatomic, retain) IBOutlet UIView *valueView;
@end
NameCell.m:
@implementation NameCell
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
UIView *nameView = [[UIView alloc] init];
self.nameView = nameView;
[self.contentView addSubview:self.nameView];
UILabel *nameLabel = [[UILabel alloc] init];
self.nameLabel = nameLabel;
[self.nameView addSubview:self.nameLabel];
NSDictionary *views = NSDictionaryOfVariableBindings(nameView, nameLabel);
NSArray *constraints;
// The constraint that should be overridden
constraints = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|[nameView]|"
options: 0
metrics:nil
views:views];
[self.contentView addConstraints:constraints];
}
return self;
}
@end
NameValueCell.m:
@implementation NameValueCell
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
NSString *reuseID = reuseIdentifier;
UIView *valueView = [[UIView alloc] init];
self.valueView = valueView;
[self.contentView addSubview:self.valueView];
NSDictionary *views = @{
@"nameView": self.nameView,
@"nameLabel": self.nameLabel,
@"valueView": self.valueView
};
NSArray *constraints;
// The overriding constraint
constraints = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|[nameView][valueView(==nameView)]|"
options: 0
metrics:nil
views:views];
[self.contentView addConstraints:constraints];
}
return self;
}
@end
【问题讨论】:
标签: ios objective-c autolayout nslayoutconstraint ios-autolayout