在显示视图之前,根据特定宽度获取UIView的高度

时间:2016-12-21 12:53:41

标签: ios swift uiview autolayout nslayoutconstraint

我在Interface Builder中设计了UIView。它基本上由标题图像和下面的一些文本(UILabel)组成。视图以模态显示,具有自定义过渡,并且不会填满整个屏幕。

左侧和右侧有20像素的边距,顶部有40像素的边距。 UILabel充满了来自网络的一些文字。我想要做的是找到(或者我应该说预测)特定宽度的整个视图的高度。我怎样才能做到这一点?

3 个答案:

答案 0 :(得分:1)

在计算预期大小之前,您需要同时拥有图片和标签。 我想你应该使用这样的东西(可能将imageView和Label之间的垂直间距加到总和上,也可以从宽度上移除横向边距):

目标C

- (CGFloat)preferredHeightFromWidth:(CGFloat)width text:(NSString *)text font:(UIFont *)font image:(UIImage *)image
{
    // Calculate label height
    CGFloat labelHeight = [text
                           boundingRectWithSize:CGSizeMake(width, 10000)
                           options:NSStringDrawingUsesLineFragmentOrigin
                           attributes:@{NSFontAttributeName:font}
                           context:[[NSStringDrawingContext alloc] init]
                           ].size.height;

    // Calculate image height
    CGFloat ratio = image.size.height/ image.size.width;
    CGFloat imageHeight = (ratio * width);

    // Do the sum
    return labelHeight + imageHeight;
}

<强>夫特

func preferredHeight(width: CGFloat, text: NSString, font: UIFont, image: UIImage) -> CGFloat {
    // Calculate Label Height
    let labelRect = text.boundingRect(
        with: CGSize.init(width: width, height: 10000),
        options: .usesLineFragmentOrigin,
        attributes: [NSFontAttributeName : font],
        context: NSStringDrawingContext())
    let labelHeight = labelRect.height

    // Calculate Image Height
    let ratio = image.size.height / image.size.width
    let imageHeight = ratio / width

    // Calculate Total Height
    let height = labelHeight + imageHeight

    // Return Height Value
    return height
}

(感谢Christopher Hannah的快速版)

答案 1 :(得分:1)

我遇到了类似的问题,但您可以使用此UIView扩展程序来自动调整视图的最大宽度,而不是计算字体大小和图像高度:

extension UIView {

    func autosize(maxWidth: CGFloat) {

        translatesAutoresizingMaskIntoConstraints = false

        let dummyContainerView = UIView(frame: CGRect(x: 0, y: 0, width: maxWidth, height: 10000000))
        dummyContainerView.addSubview(self)
        dummyContainerView.topAnchor.constraint(equalTo: topAnchor, constant: 0).isActive = true
        dummyContainerView.leftAnchor.constraint(equalTo: leftAnchor, constant: 0).isActive = true
        dummyContainerView.rightAnchor.constraint(equalTo: rightAnchor, constant: 0).isActive = true

        setNeedsLayout()
        layoutIfNeeded()

        removeFromSuperview()

        frame = CGRect(x: 0, y: 0, width: frame.width, height: frame.height)

        translatesAutoresizingMaskIntoConstraints = true
    }
} 

使用此approuch,您不必担心视图中的内容。

使用它:

let customView: CustomView = ... //create your view
... // configure all data on your view, e.g. labels with correct text
customView.autosize(maxWidth: 150) // resize your view 
view.addSubview(customView) // add your view to any view

答案 2 :(得分:0)

以下是与Alberto相同的答案,但我已将其更改为Swift 3。

{{1}}