【问题标题】:UIButton with single press and long press events swift具有单按和长按事件的 UIButton 快速
【发布时间】:2015-06-16 05:04:59
【问题描述】:

我想在button clickbutton long click 上触发两个操作。我在界面生成器中添加了UIbutton。我如何使用IBAction 触发两个操作,有人可以告诉我如何存档吗?

这是我用来点击按钮的代码

@IBAction func buttonPressed (sender: UIButton) { .... }

我可以使用这种方法还是必须使用其他方法进行长按?

【问题讨论】:

标签: ios iphone swift uibutton


【解决方案1】:

如果您想通过单击执行任何操作并长按您可以通过这种方式将手势添加到按钮中:

@IBOutlet weak var btn: UIButton!

override func viewDidLoad() {

    let tapGesture = UITapGestureRecognizer(target: self, #selector (tap))  //Tap function will call when user tap on button
    let longGesture = UILongPressGestureRecognizer(target: self, #selector(long))  //Long function will call when user long press on button.
    tapGesture.numberOfTapsRequired = 1
    btn.addGestureRecognizer(tapGesture)
    btn.addGestureRecognizer(longGesture)
}

@objc func tap() {

    print("Tap happend")
}

@objc func long() {

    print("Long press")
}

这样你可以为单个按钮添加多个方法,你只需要那个按钮的 Outlet ..

【讨论】:

  • 我的 ui 中有多个按钮,因为它们都执行相同的操作,因此我已将它们映射到此方法 (@IBAction func buttonPressed (sender: UIButton),我可以通过编程方式添加方法吗?
  • 然后你需要为所有按钮创建出口并添加这个手势。这个方法将适用于所有按钮。
  • 哦,我的 ui 中有 30 个按钮,它是一个键盘 :( 有没有办法在不使用插座的情况下将它们存档?
  • 我认为没有。如果您想通过长按执行操作,则必须为所有人创建插座并添加手势。:)
  • 我们可以以编程方式映射 IBAction 吗?所以我只需要为一个按钮创建插座
【解决方案2】:
@IBOutlet weak var countButton: UIButton!
override func viewDidLoad() {
    super.viewDidLoad()

    addLongPressGesture()
}
@IBAction func countAction(_ sender: UIButton) {
    print("Single Tap")
}

@objc func longPress(gesture: UILongPressGestureRecognizer) {
    if gesture.state == UIGestureRecognizerState.began {
        print("Long Press")
    }
}

func addLongPressGesture(){
    let longPress = UILongPressGestureRecognizer(target: self, action: #selector(longPress(gesture:)))
    longPress.minimumPressDuration = 1.5
    self.countButton.addGestureRecognizer(longPress)
}

【讨论】:

    【解决方案3】:

    为什么不创建一个自定义 UIButton 类,创建一个协议并让按钮将信息发送回委托。像这样的:

        //create your button using a factory (it'll be easier of course)
        //For example you could have a variable in the custom class to have a unique identifier, or just use the tag property)
    
        func createButtonWithInfo(buttonInfo: [String: Any]) -> CustomUIButton {
            let button = UIButton(type: .custom)
            button.tapDelegate = self
            /*
    Add gesture recognizers to the button as well as any other info in the buttonInfo
    
    */
            return button
        }
    
        func buttonDelegateReceivedTapGestureRecognizerFrom(button: CustomUIButton){
            //Whatever you want to do
        }
    

    【讨论】:

      猜你喜欢
      • 2011-09-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-30
      • 1970-01-01
      • 2023-04-02
      • 1970-01-01
      相关资源
      最近更新 更多