您如何以编程方式制作 UIViews,它们是其中 textLabels 的高度? (在Swift)

How do you programmatically make UIViews which are the height of textLabels inside them? (In Swift)

我正在尝试制作 UIView,每个 UIView 都包含不同的文本语句(在 UITextView 中)。可以有不同数量的视图,并且每个语句的长度可以不同。我使用

制作这些视图
let newView = DragView(heightOfView: ???, viewNumber: i, heightFromTop: currentHeightForThings)

在 DragView class 中,然后我使用 viewNumber 访问该语句,并将该语句放在我制作的 nib 文件中的文本标签中。

我的问题是我没有东西可以放入 heightOfView。我想要的高度是 textLabel 的高度,它根据语句的 textView 中的行数而变化。但是我无法访问此高度,因为尚未构建 textLabel。

在此先感谢,我是 swift 的新手,但想快速学习,所以如果我遗漏了一些明显的东西,我深表歉意!


这是我在 class DragView

中的代码
class DragView: UIView {

    @IBOutlet var dragView: UIView!
    @IBOutlet weak var statementLabel: UITextView!

    var dropTarget: UIView?
    var viewNumber: Int!

    init(heightOfView: Int, viewNumber:Int, heightFromTop: Int) {
        self.viewNumber = viewNumber
        let startingPosition = CGRect(x: Int(widthCentre) - dragViewWidth / 2, y: heightFromTop, width: dragViewWidth, height: heightOfView)
        super.init(frame: startingPosition)

        NSBundle.mainBundle().loadNibNamed("DragView", owner: self, options:  nil)

        self.addSubview(self.dragView)
        let movingView = MovingView(frame: startingPosition)
        self.addSubview(movingView)
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
}

这里的 movingView 是我在视图上添加的子视图,用于移动视图。

您可以覆盖 DragViewsizeThatFits 方法,使其 return 的高度基于 statementLabel 的高度。您必须先在 textView 上调用 sizeToFit,这将设置该视图的高度,然后 return 基于此的高度。

override func sizeThatFits(size: CGSize) -> CGSize {
    self.statementLabel.sizeToFit()
    return CGSize(
        width: self.frame.width, 
        height: self.statementLabel.frame.height)
}

此外,如果您要进行程序化布局,我建议您查看 sizeThatFitslayoutSubviews。子视图的大小和定位应该发生在 layoutSubviews 而不是 init.