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])
}
}
}
结果如下:
但我希望实现以下目标:
如何?
答案 0 :(得分:0)
请尝试将UILabel
的框架设置为与UITextView
的框架相同。
placeholderLabel.frame = CGRect(x: 0, y: 0, width: self.bounds.width, height: self.bounds.height)