我正在创建一个 MDCOutlinedTextArea 并将其添加到容器视图中,使用以下代码:
let textArea = MDCOutlinedTextArea(frame: container.frame)
textArea.label.text = placeholder
textArea.placeholder = placeholder
let fontSize: CGFloat = 14
let font = UIFont(name: GlobalVariables.FONT_NAME, size: fontSize)!
textArea.label.font = font
textArea.textView.font = font
textArea.sizeToFit()
container.addSubview(textArea)
textArea.bindFrameToSuperviewBounds()
bindFrameToSuperViewBounds 方法是一个扩展方法,它可以做到:
func bindFrameToSuperviewBounds(_ margin : CGFloat = 2) {
guard let superview = self.superview else {
print("Error! `superview` was nil – call `addSubview(view: UIView)` before calling `bindFrameToSuperviewBounds()` to fix this.")
return
}
self.translatesAutoresizingMaskIntoConstraints = false
self.topAnchor.constraint(equalTo: superview.topAnchor, constant: margin).isActive = true
self.bottomAnchor.constraint(equalTo: superview.bottomAnchor, constant: margin).isActive = true
self.leadingAnchor.constraint(equalTo: superview.leadingAnchor, constant: margin).isActive = true
self.trailingAnchor.constraint(equalTo: superview.trailingAnchor, constant: margin).isActive = true
//self.heightAnchor.constraint(equalToConstant: superview.frame.size.height).isActive = true
}
好吧,问题是文本区域没有使用容器视图的整个高度:
如图所示,容器比文本区域更大,但文本区域拒绝增长。
我设法通过设置行数使它更大:
let numberOfRows = container.frame.height / font.lineHeight
textArea.minimumNumberOfVisibleRows = numberOfRows
尽管该代码运行不佳,因为行的计算返回的行数超过了所需的行数。我真的不知道如何计算文本区域的行数。
我遇到的另一个问题是我无法为文本区域设置边距。正如您在源代码中看到的,我尝试使用约束给文本区域一些边距。它似乎适用于顶部和前导约束,但不适用于尾随和底部约束。
一些想法?