美文网首页
Swift 中给UITextView添加占位文字

Swift 中给UITextView添加占位文字

作者: 漩涡长门 | 来源:发表于2017-10-31 19:11 被阅读3次
  • 先创建一个UILabel

// MARK: - 懒加载
    private lazy var placeholderLabel: UILabel =
        {
            let lb = UILabel()
            lb.textColor = UIColor.lightGray
            lb.text = "占位文字"
            lb.font = self.font
            return lb
    }()
  • 将创建的label加入到UITextView中 布局label的位置

    addSubview(placeholderLabel)
        placeholderLabel.snp.makeConstraints { (make) in
            make.top.equalTo(5)
            make.left.equalTo(5)
        }
  • 使用通知监听UITextView是否有输入数据,有数据隐藏label

      NotificationCenter.default.addObserver(self, selector:   #selector(textChange), name:   NSNotification.Name.UITextViewTextDidChange, object: self)

  func textChange(){
      //hasText 可以监听UITextView是否有值输入返回Bool类型
        placeholderLabel.isHidden = hasText
    }
  • 移除通知

       deinit {
        NotificationCenter.default.removeObserver(self)
    }

相关文章

网友评论

      本文标题:Swift 中给UITextView添加占位文字

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