是否可以从被认为是 .touchDragExit(或 .touchDragEnter)的按钮自定义区域(超出其可选区域?)?
更具体地说,我说的是这种情况:我点击 UIButton,.touchDown 被调用,然后我开始将我的手指从按钮上拖开,在某个点(一段距离)它将不再选择(当然我可以拖回去选择...)。我想要修改那个距离...
这可能吗?
最佳答案
您需要覆盖 UIButton
continueTracking
和 touchesEnded
函数。
改编@Dean的链接,实现如下(swift 4.2):
class ViewController: UIViewController {
@IBOutlet weak var button: DragButton!
override func viewDidLoad() {
super.viewDidLoad()
}
}
class DragButton: UIButton {
private let _boundsExtension: CGFloat = 0 // Adjust this as needed
override open func continueTracking(_ touch: UITouch, with event: UIEvent?) -> Bool {
let outerBounds: CGRect = bounds.insetBy(dx: CGFloat(-1 * _boundsExtension), dy: CGFloat(-1 * _boundsExtension))
let currentLocation: CGPoint = touch.location(in: self)
let previousLocation: CGPoint = touch.previousLocation(in: self)
let touchOutside: Bool = !outerBounds.contains(currentLocation)
if touchOutside {
let previousTouchInside: Bool = outerBounds.contains(previousLocation)
if previousTouchInside {
print("touchDragExit")
sendActions(for: .touchDragExit)
} else {
print("touchDragOutside")
sendActions(for: .touchDragOutside)
}
} else {
let previousTouchOutside: Bool = !outerBounds.contains(previousLocation)
if previousTouchOutside {
print("touchDragEnter")
sendActions(for: .touchDragEnter)
} else {
print("touchDragInside")
sendActions(for: .touchDragInside)
}
}
return true
}
override open func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
let touch: UITouch = touches.first!
let outerBounds: CGRect = bounds.insetBy(dx: CGFloat(-1 * _boundsExtension), dy: CGFloat(-1 * _boundsExtension))
let currentLocation: CGPoint = touch.location(in: self)
let touchInside: Bool = outerBounds.contains(currentLocation)
if touchInside {
print("touchUpInside action")
return sendActions(for: .touchUpInside)
} else {
print("touchUpOutside action")
return sendActions(for: .touchUpOutside)
}
}
}
尝试更改 _boundsExtension
值
关于ios - 自定义 UIButton .touchDragEnter 和 .touchDragExit 区域/大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57120346/