UIHandlers 1.6.1

UIHandlers 1.6.1

Brandon Erbschloe维护。



  • 作者:
  • Brandon Erbschloe

UIHandlers

Swift CocoaPods SwiftPm

为具有UIGestureRecognizers的UIControls和UIView添加闭包支持。

要求

  • iOS 9.0+
  • Xcode 10.2+
  • Swift 5.0+

安装

CocoaPods

CocoaPods是一个Cocoa项目的依赖管理器。有关使用和安装说明,访问他们的网站。要使用CocoaPods将库集成到Xcode项目中,请在您的Podfile中指定它。

pod 'UIHandlers', '1.6.1'

Swift包管理器

Swift包管理器是一个用于自动化Swift代码发布的工具,并集成到了swift编译器中。

dependencies: [
    .package(url: "https://github.com/berbschloe/UIHandlers.git", from: "1.6.1")
]

使用

导入

建议全局添加库,因为它在到处导入时可能会很麻烦。

// Add this to a GlobalImports.swift
@_exported import UIHandlers

向控件添加事件处理器

监听控件事件的常规方式

func viewDidLoad() {
    super.viewDidLoad()
    
    let button = UIButton()
    
    button.addTarget(self, action: #selector(doSomething), for: .primaryActionTriggered)
}

@objc
private func doSomething() { ... }

直接向控件添加处理器

func viewDidLoad() {
    super.viewDidLoad()
    
    let button = UIButton()

    // [unowned self] is needed to prevent reference cycles
    button.addHandler(for: .primaryActionTriggered) { [unowned self] in
        self.doSomething();
    }
}

添加具有多个参数的处理器的处理

button.addHandler(for: .primaryActionTriggered) { ... }
button.addHandler(for: .primaryActionTriggered) ( (sender: UIButton) in ... }
button.addHandler(for: .primaryActionTriggered) ( (sender: UIButton, event: UIEvent) in ... }

向视图中添加用于手势识别的处理器的处理

向视图添加手势识别器的常规方法

func viewDidLoad() {
    super.viewDidLoad()
    
    let view = UIView()

    let gesture = UITapGestureRecognizer(target: self, action: #selector(doSomething))
    view.addGestureRecognizer(gesture)
}

@objc
private func doSomething() { ... }

向视图添加轻触手势识别器

func viewDidLoad() {
    super.viewDidLoad()
    
    let view = UIView()
    
    view.addTapHandler() { [unowned self] in
        self.doSomething()
    }
}

添加轻触手势的更多变体

// tap handler with paramater
view.addTapHandler() { (gesture: UITapGestureRecognizer) in ... }

// controling the number of taps
view.addTapHandler(numberOfTapsRequired: 42) { ... }

其他支持的手势识别器

view.addDoubleTapHandler() { ... }
view.addLongPressHandler() { ... }
view.addPanHandler() { ... }
view.addSwipeHandler(direction: .right) { ... }
view.addPinchHandler() { ... }
view.addRotationHandler() { ... }
view.addScreenEdgePanHandler(edges: .right) { ... }