swift 自定义适配系统UItextview

通过系统自带的方法实现UItextview内边距、placehodler和开始编辑后的不同颜色、最多显示三行、行高。

看看效果
image.png

image.png
  
    lazy var textView: UITextView = {
        let textView = UITextView()
        textView.text = "填写后会被系统推荐"
        textView.font = UIFont.systemFont(ofSize: 14)
        textView.textColor = UIColor("#AEAEB2")
        textView.textContainerInset = UIEdgeInsets(top: 16, left: 16, bottom: 16, right: 16)
        textView.textContainer.maximumNumberOfLines = 3
        textView.textContainer.lineBreakMode = .byTruncatingTail
        textView.delegate = self
        textView.clipsToBounds = true
        textView.layer.cornerRadius = 8
        textView.bounces = false
        textView.isScrollEnabled = false
        textView.backgroundColor = ColorBackgroundColor6
        return textView
    }()
 

//MARK: -UITextViewDelegate
extension UserEditCell: UITextViewDelegate{
    func textViewDidBeginEditing(_ textView: UITextView) {
        textView.text = ""
    }
    
    func textViewDidChange(_ textView: UITextView) {
        
        textView.textColor = UIColor("#636366")
        //设置行间距
        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.lineSpacing = 4
//        let content = "今天又在想,我们做很多事情,学习新的东西、认真工作、健身,都是为了让自己更喜欢自己一点。我喜欢我的时候,谁不喜欢我都没关系,开开心心的过好每一天。"
        if let content = textView.text{
            let attributedText = NSMutableAttributedString(string: content)
            attributedText.addAttribute(NSAttributedString.Key.paragraphStyle, value: paragraphStyle, range: NSRange(location: 0, length: content.count))
            textView.attributedText = attributedText
        }
      
    }
    
}

你可能感兴趣的:(swift 自定义适配系统UItextview)