一般情况下按钮都是只能一次一次的按,那如果像添加商品那种可以长按的又该怎么做呢。
设置Button的ControlEvent(不行的)
一步一步来,如果我们当按钮按下的时候我们处理按钮按下的消息可不可以呢,来我们看一下UIControlEvents.touchDown会不会一直触发:
let button = UIButton(type: UIButtonType.system)
var count = 0
override func viewDidLoad() {
super.viewDidLoad()
button.addTarget(self, action: #selector(handleAction), for: UIControlEvents.touchDown)
button.backgroundColor = UIColor.red
button.bounds = CGRect(x: 0, y: 0, width: 100, height: 100)
button.center = self.view.center
self.view.addSubview(button)
}
@objc func handleAction() {
count += 1
print(count)
}
结果如下图:
control_touchDown就只打印了一次,很显然这是不行的。那我们再试一试其它的方法。
给Button添加长按手势(不行的)
那touchDown只能触发一次,那我们给Button添加长按手势会怎样呢?
参考
//来来来,我们加一个长按手势
let longPressd = UILongPressGestureRecognizer(target: self, action: #selector(handleAction))
button.addGestureRecognizer(longPressd)
结果如下图:
control_touchDown
哎,可以了啊,终于搞定了😆,但是仔细观察一下控制台的打印,长按手势的触发并不均匀。这导致了什么呢,如果你加商品的时候,我按了下去,一下就加了5,6件,也可能加了2,3件,这样体验不好啊。看来添加长按手势也是不行的。
给Button加个Timer吧
那我们又想要多次触发又想要时间均匀,那我们给button加上个timer,当按钮按下的时候我们就开启,当手离开的时候我们就停止不就行了么,说干就干。
//我们给button加上这些状态
//在touchDown(按钮按下)的状态的时候开启计时器
button.addTarget(self, action: #selector(startTimer), for: UIControlEvents.touchDown)
//在touchCancel,touchUpInside,touchUpOutside(按钮松开)的状态的时候停止计时器
button.addTarget(self, action: #selector(stopTimer), for: UIControlEvents.touchCancel)
button.addTarget(self, action: #selector(stopTimer), for: UIControlEvents.touchUpInside)
button.addTarget(self, action: #selector(stopTimer), for: UIControlEvents.touchUpOutside)
//然后再加上计时器的方法 设置为每隔1秒触发一次
@objc func startTimer() {
timer = Timer(timeInterval: TimeInterval(1), target: self, selector: #selector(handleAction), userInfo: nil, repeats: true)
RunLoop.current.add(timer, forMode: .commonModes)
}
@objc func stopTimer() {
timer.invalidate()
}
结果如下:
longpressed_timer
Good!结果很漂亮,每隔1秒触发,间隔很均匀,自己也可手动调整触发的时间间隔。
(ps:至于按钮的话就自己封装了)
End
我自己封装了一个基于RxSwift的长按按钮LongPressButton,欢迎star
网友评论