美文网首页
Swift UITextView placeholder

Swift UITextView placeholder

作者: YourSummer | 来源:发表于2023-06-20 09:11 被阅读0次

网上有多种给UITextview添加占位字符的方案, 我最喜欢这一种:

import UIKit

extension UITextView {
    
    var placeholder: String {
        set {
            let lb = UILabel()
            lb.font = font
            lb.numberOfLines = 0
            lb.textColor = .lightGray
            lb.text = newValue
            addSubview(lb)
            setValue(lb, forKey: "_placeholderLabel")
        }
        get {
            let lb = value(forKey: "_placeholderLabel") as? UILabel
            return lb?.text ?? ""
        }
    }
}

示例:

let textView = UITextView()
textView.placeholder = "请给个小心心"

相关文章

网友评论

      本文标题:Swift UITextView placeholder

      本文链接:https://www.haomeiwen.com/subject/xdsyydtx.html