专业java、php、iOS、C++、网页设计、平面设计、网络营销、游戏开发、前端与移动开发培训机构

显示微博文字剩余长度

  • HMComposeViewController.xib 中 添加 剩余微博文本长度 Label
  • 定义 微博文本最大长度
    /// 微博文本最大长度
    private let statusMaxLength = 20
    
  • 定义 setupTipLabel 方法,设置长度
    /// 设置长度label
    private func setupTipLabel() {
      lengthTipLabel.text = "\(statusMaxLength)"
    }
    
  • viewDidLoad 方法里面调用 setupTipLabel

    override func viewDidLoad() {
      super.viewDidLoad()
    
      // 添加键盘frame改变的通知
      NotificationCenter.default.addObserver(self, selector: #selector(willChangeFrame(notification:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
    
      textView.delegate = self
    
      setNavigationBar()
      setToolBar()
      setupTipLabel()
      ...
    }
    
  • 在文本发生 改变 的时候 重新计算 剩余文本长度

    // 文字改变代理方法
    extension HMComposeViewController: UITextViewDelegate {
      func textViewDidChange(_ textView: UITextView) {
          sendButton.isEnabled = textView.hasText
    
          // 计算剩余文本的长度
          let text = textView.emoticonText()
    
          let length = statusMaxLength - text.characters.count
    
          // 设置文本内容
          lengthTipLabel.text = "\(length)"
    
          // 设置文本颜色, length < 0 红色
          lengthTipLabel.textColor = length < 0 ? UIColor.red : UIColor.lightGray
      }
    }
    

results matching ""

    No results matching ""