UITextView添加Placeholder(swift)

來源:互聯網
上載者:User

標籤:ios

UITextView添加Placeholder(swift)by 伍雪穎
添加UILabel並初始化
public let placeholderLabel: UILabel = UILabel()
@IBInspectable publicvar placeholder: String ="" {
        didSet {
            placeholderLabel.text =placeholder
        }
    }
    
@IBInspectable publicvar placeholderColor: UIColor =UIColor(red: 0.0, green:0.0, blue: 0.0980392, alpha:0.22) {
        didSet {
            placeholderLabel.textColor =placeholderColor
        }
    }
override publicvar font: UIFont! {
        didSet {
            placeholderLabel.font =font
        }
    }
    
override publicvar textAlignment: NSTextAlignment {
        didSet {
            placeholderLabel.textAlignment =textAlignment
        }
    }
addSubview添加上去
override init(frame:CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        commonInit()
    }
    
    required publicinit(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        commonInit()
    }
    
    func commonInit() {
        NSNotificationCenter.defaultCenter().addObserver(self,
            selector: "textDidChange",
            name: UITextViewTextDidChangeNotification,
            object: nil)
        
        placeholderLabel.font =font
        placeholderLabel.textColor =placeholderColor
        placeholderLabel.textAlignment =textAlignment
        placeholderLabel.text =placeholder
        placeholderLabel.numberOfLines =0
        placeholderLabel.backgroundColor =UIColor.clearColor()
        placeholderLabel.setTranslatesAutoresizingMaskIntoConstraints(false)
        addSubview(placeholderLabel)
    }

輸入文字消失的事件
override publicvar text: String! {
        didSet {
            textDidChange()
        }
    }

func textDidChange() {
        placeholderLabel.hidden = !text.isEmpty
    }



UITextView添加Placeholder(swift)

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.