【问题标题】:Manual set the height of UILable with autolayout手动设置UILabel宽度自动布局的高度
【发布时间】:2014-12-23 06:58:16
【问题描述】:

我的自定义单元格中有一个动态高度的UIlabel,高度值是通过方法计算的:

- (CGRect)boundingRectWithSize:(CGSize)size options:(NSStringDrawingOptions)options attributes:(NSDictionary *)attributes context:(NSStringDrawingContext *)context

然后我通过传递之前计算的值来调用以下方法:

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath

但是,问题是我不能简单地设置label.frame = newFrame 以适应其内容,因为自动布局。

而且,我不想对故事板中的元素设置太多限制。我真正需要的是像lable.constraint.height = newHeight 这样的单行代码,有什么想法吗?

【问题讨论】:

    标签: ios uilabel autolayout constraints


    【解决方案1】:

    为你的标签设置约束。

    [yourlabel setNeedsUpdateConstraints];
    
    [yourlabel setTranslatesAutoresizingMaskIntoConstraints:NO]; 
    
    NSLayoutConstraint *constraintHeight = [NSLayoutConstraint constraintWithItem:yourlabel
                                                                            attribute:NSLayoutAttributeHeight
                                                                            relatedBy:NSLayoutRelationEqual
                                                                               toItem:nil
                                                                            attribute:NSLayoutAttributeNotAnAttribute
                                                                           multiplier:1.0
                                                                             constant:newheight];
    
    [yourlabel addConstraints:@[constraintHeight]];
    

    【讨论】:

    • 这对我不起作用,似乎无法添加新的约束。顺便说一句,我在进行单元配置时添加了此代码。
    • 尝试将其添加到您的自定义单元格类中
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-01
    • 2016-03-09
    • 1970-01-01
    • 2014-02-11
    • 2014-01-14
    • 2019-06-20
    相关资源
    最近更新 更多