添加UILabel作为UITextView的子视图,带有换行符,没有水平指示符

时间:2017-06-07 20:51:10

标签: ios swift

AttributedTextView的自定义子类UITextView

@IBDesignable class AttributedTextView: UITextView {

private let placeholderLabel = UILabel(frame: .zero)

override func awakeFromNib() {
    super.awakeFromNib()

    setupPlaceholderLabelIfNeeded()
}

private func setupPlaceholderLabelIfNeeded() {

    if placeholderLabel.superview == nil {

        placeholderLabel.font = UIFont.openSansLight(withSize: 21)
        placeholderLabel.translatesAutoresizingMaskIntoConstraints = false
        placeholderLabel.frame = CGRect(x: 0, y: 0, width: 100, height: 100)
        placeholderLabel.textColor = UIColor.lightGray
        placeholderLabel.text = placeholder.localized
        placeholderLabel.numberOfLines = 0

        let leading = NSLayoutConstraint(item: placeholderLabel, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1, constant: 0)
        let trailing = NSLayoutConstraint(item: placeholderLabel, attribute: .trailing, relatedBy: .equal, toItem: self, attribute: .trailing, multiplier: 1, constant: 0)
        let top = NSLayoutConstraint(item: placeholderLabel, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1, constant: 0)
        let bottom = NSLayoutConstraint(item: placeholderLabel, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1, constant: 0)

        addSubview(placeholderLabel)
        addConstraints([leading, trailing, top, bottom])
    }
}
}

结果如下:

enter image description here

但我希望实现以下目标:

enter image description here

如何?

1 个答案:

答案 0 :(得分:0)

请尝试将UILabel的框架设置为与UITextView的框架相同。

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