Ty *_*ton 16 constraints uitableview ios layoutsubviews autolayout
我正在尝试将autolayout用于我正在创建的uitableviewcell子类,我将非常感谢有关放置布局约束创建代码的方法的一些建议.我一直在搜索并找到有关在viewDidLoad方法中添加子视图后添加约束的所有信息.据我所知,viewDidLoad不是uitableviewcell子类的选项.
我正在使用界面构建器来创建自定义单元格并在我的代码中动态分配它.没有什么特别的......我将uitableviewcell子类化,以便我可以向单元格添加自定义uiview.再一次,没有什么特别令人震惊的......当我尝试根据我添加到界面构建器中的单元格的标签来定位我的自定义uiview时,我遇到了困难.
这是创建自定义uiview并将其添加到单元格内容视图的代码:
- (id)initWithCoder:(NSCoder *)decoder
{
if ((self = [super initWithCoder:decoder]))
{
[self initSelf];
}
return self;
}
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
if ((self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]))
{
[self initSelf];
}
return self;
}
- (void) initSelf
{
// Initialization code
_badgeLabel = @"";
if (!_customBadge)
{
_customBadge = [CustomBadge customBadgeWithString:self.badgeLabel];
}
// hide the badge until needed
self.customBadge.hidden = YES;
// add badge to the cell view hierarchy
[self.customBadge setTranslatesAutoresizingMaskIntoConstraints:NO];
[self.customBadge setContentHuggingPriority:UILayoutPriorityDefaultHigh forAxis:UILayoutConstraintAxisHorizontal];
[self.customBadge setContentHuggingPriority:UILayoutPriorityDefaultHigh forAxis:UILayoutConstraintAxisVertical];
[self.contentView addSubview:self.customBadge];
}
Run Code Online (Sandbox Code Playgroud)
如果我把约束代码放在initSelf的末尾没有任何反应.我的_customBadge的位置保持在'默认值.当我将约束代码放在layoutSubviews中时,应用了定位; 但我很确定这是错误的地方.这是代码:
- (void) layoutSubviews
{
[self.contentView addConstraint:[NSLayoutConstraint
constraintWithItem:self.customBadge
attribute:NSLayoutAttributeLeft
relatedBy:NSLayoutRelationEqual
toItem:self.competence
attribute:NSLayoutAttributeRight
multiplier:1.0
constant:-14.0]];
[self.contentView addConstraint:[NSLayoutConstraint
constraintWithItem:self.customBadge
attribute:NSLayoutAttributeTop
relatedBy:NSLayoutRelationEqual
toItem:self.competence
attribute:NSLayoutAttributeTop
multiplier:1.0
constant:0.0]];
[super layoutSubviews];
}
Run Code Online (Sandbox Code Playgroud)
谁能告诉我这段代码应该去哪里?当然,每次布局发生时我都会创建重复的约束.
谢谢
Adr*_*ian 31
您需要更新约束,如:
-(void)updateConstraints{
// add your constraints if not already there
[super updateConstraints];
}
Run Code Online (Sandbox Code Playgroud)
将视图添加到superview后,您需要调用[self setNeedsUpdateConstraints]以开始使用它们.通过这样做,渲染运行时将updateConstraints在正确的时间调用.
| 归档时间: |
|
| 查看次数: |
19167 次 |
| 最近记录: |