ytyubox / YuBlog

這是用來記錄的Blog,紀錄內容在 Issues 頁面中。
0 stars 0 forks source link

20190407 使用閉包解決UIButton 耦合問題 #20

Open ytyubox opened 5 years ago

ytyubox commented 5 years ago
class Button:UIButton{
  typealias Handler = (Button)->Void

  var tapHandle:Handler!
  var longHandle:Handler?
  var longPressTime:TimeInterval{
    get { return longGesture.minimumPressDuration }
    set { longGesture.minimumPressDuration = newValue}
  }
  private
  var longGesture:UILongPressGestureRecognizer!

  convenience init(type:UIButton.ButtonType = .custom,
                   defaultEvent event:UIControl.Event = .touchUpInside,
                   handle:@escaping Handler) {
    self.init(type:.custom)
    addTarget(self, action: #selector(tapped), for: event)
    longGesture = UILongPressGestureRecognizer(target: self, action: #selector(long))
    addGestureRecognizer(longGesture)
    self.tapHandle = handle
    setTitle("Default Title", for: [])
    sizeToFit()
    translatesAutoresizingMaskIntoConstraints = false
  }
  @objc
  private func tapped(){
  tapHandle(self)
  }
  @objc
  private func long(){
    longHandle?(self)
  }
}