摘要:本文将带你了解IOS开发入门【iOS】自定义控件之长按按钮,希望本文对大家学IOS有所帮助。
本文将带你了解IOS开发入门【iOS】自定义控件之长按按钮,希望本文对大家学IOS有所帮助。
【iOS】自定义控件之长按按钮
需求
最近接了一个需求,长按一个按钮,需要持续的触发,手指抬起时或者离开按钮触摸区域,就结束响应。
思路
思路1:在button上添加一个长按手势。
思路2:给button添加一个定时器
实现
最后笔者使用了思路2的方法,采用了定时器。采用定时器最需要解决的一个问题是,定时器的关闭,于是笔者把所有能想到可以停止定时器的情况都会调用一次~
代码如下:
/// 只要手放在button上就会触发
class TouchButton: UIButton {
fileprivate var target: AnyObject?
fileprivate var action: Selector!
fileprivate var timer: Timer?
/// 记录timer执行次数
var count: Int = 1
/// 记录增量
var increament: Int = 1
deinit {
touchUp()
}
/// 添加事件
func addTouch(_ target: AnyObject?, action: Selector) {
self.addTarget(self, action: #selector(touchDown), for: .touchDown)
self.addTarget(self, action: #selector(touchUp), for: .touchUpInside)
self.target = target
self.action = action
}
/// 判断是否取消定时器,超出按钮边界时,取消定时器
override func touchesMoved(_ touches: Set<uitouch>, with event: UIEvent?) {
let p = (touches as NSSet).anyObject()
let touch = p as! UITouch
let point = touch.location(in: self)
// 超出边界时,取消定时器
if point.x < 0 || point.x > self.frame.width || point.y < 0 || point.y > self.frame.height {
touchUp()
}
}
override func touchesCancelled(_ touches: Set<uitouch>, with event: UIEvent?) {
touchUp()
}
override func touchesEnded(_ touches: Set<uitouch>, with event: UIEvent?) {
touchUp()
}
func touchDown() {
self.timer?.invalidate()
target?.perform(action)
let timer = Timer(timeInterval: 0.1, target: target!, selector: action, userInfo: nil, repeats: true)
RunLoop.current.add(timer, forMode: RunLoopMode.defaultRunLoopMode)
self.timer = timer
}
func touchUp() {
timer?.invalidate()
count = 1
increament = 1
}
}</uitouch></uitouch></uitouch>
注意
/// 记录timer执行次数
var count: Int = 1
/// 记录增量
var increament: Int = 1
关于这两个字段,是因为外部需要控制其触发速率而添加的属性,你也可以根据自己的业务要求,适当的添加一些属性~
本文由职坐标整理并发布,希望对同学们有所帮助。了解更多详情请关注职坐标移动开发之IOS频道!
您输入的评论内容中包含违禁敏感词
我知道了
请输入正确的手机号码
请输入正确的验证码
您今天的短信下发次数太多了,明天再试试吧!
我们会在第一时间安排职业规划师联系您!
您也可以联系我们的职业规划师咨询:
版权所有 职坐标-一站式IT培训就业服务领导者 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
沪公网安备 31011502005948号