ios - 添加一个 UILabel 作为 UITextView 的 subview ,带有换行符且没有水平指示器

标签 ios swift

我的UITextView的自定义子类AttributedTextView:

@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

如何?

最佳答案

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

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

关于ios - 添加一个 UILabel 作为 UITextView 的 subview ,带有换行符且没有水平指示器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44422544/

相关文章:

ios - 如何为 Arc 做角

ios - 获取错误 "Cannot load module ' MapKit' 作为 'MapKit'“

ios - 滚动时 UIBezierPath 问题的舍入

ios - UIAlertAction 改变颜色

ios - 适当的更改不会影响表格 View 部分标题背景

ios - 如何使用 UICollectionview 播放 Facebook 风格的视频

ios - 快速避免数据竞争条件

ios - Google Place API 在 iOS App 中给出错误的结果

ios - 如何创建 UIActionSheet 操作?

swift - 将来自 firebase 子键值对的数据存储为数组