我有两个 UIButton,一个在另一个之上。第一个有一个实现视觉反馈的自定义类,另一个按钮有一个调用函数的 onClick 事件方法。
如何获取第一个按钮下的第二个按钮的onClick事件?
我需要两个按钮,以便自定义触摸区域和视觉反馈的大小。
最佳答案
不建议从子类化 UIButton
开始:) 如果您需要视觉反馈效果,您可以拥有一个 UIView
并添加一个 tapGesture
识别器。在检测到点击时你可以做
swift
let touchPoint = tapGestureRecognizer.location(in: your_view)
if your_inner_button.frame.contains(touchPoint) {
your_inner_button.sendActions(for: .touchUpInside)
}
objective-C
CGPoint point = [self.tapGesture locationInView:self];
if (CGRectContainsPoint(self.frame, point)) {
[self sendActionsForControlEvents:UIControlEventTouchUpInside];
}
上面一个没有多大意义,因为如果你已经检测到点击并确定触摸在你要求的框架内,你为什么还要触发按钮点击,直接调用 performSelector
。这样你就不会需要一个按钮和一个 View ,而你只需要一个 View
只是为了澄清可以做你想做的事,
如果由于某些未知原因,你不能这样做并且你被迫(我猜是在 Guzzle :P)使用两个彼此重叠的按钮,你总是可以使用 hitTest
将触摸切换到下面的按钮
swift
class MyButton: UIButton {
override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
if your_inner_button.frame.contains(point) {
return your_inner_button
}
return nil
}
}
objective-C
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
if (CGRectContainsPoint(your_inner_button.frame, point)) {
return your_inner_button
}
return nil;
}
要使其正常工作,您必须将下面的按钮引用传递给顶部按钮,这应该不是问题,因为您无论如何都有顶部按钮的子类 :) 代码有异味吗?对我来说是的,但它能满足你的需要吗?是的 :)
希望对你有帮助
关于ios - 点击 UIButton - ios,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52871636/