【发布时间】:2021-10-24 18:08:56
【问题描述】:
我有一系列按钮存在于其祖父视图的框架之外。现在无法单击这些按钮,并且我无法移动按钮,那么如何使它们在祖父视图的框架之外可单击?该按钮存在于一个小的圆形 UIView 内,并且该 UIView 位于其父视图的框架之外。我试过使用命中测试,但它仍然没有触发
这是我的按钮:
class ButtonNode: UIButton {
override init(frame: CGRect) {
super.init(frame: frame)
}
convenience init(frame: CGRect, agree: Bool) {
self.init(frame: frame)
setupView()
}
required init(coder aDecoder: NSCoder) {
fatalError("This class does not support NSCoding")
}
func setupView(){
self.setTitle("+10", for: .normal)
self.titleLabel?.font = UIFont.boldSystemFont(ofSize: 12)
self.setTitleColor(.lightGray, for: .normal)
self.isUserInteractionEnabled = true
self.layer.borderWidth = 1.0
self.layer.borderColor = UIColor.lightGray.cgColor
self.layer.cornerRadius = 15
}
}
这是父视图中的设置:
var rightLastNodeButton:UIButton?
var leftLastNodeButton:UIButton?
leftButton = ButtonNode(frame: CGRect(x: leftX, y: y, width: width, height: height), agree: false)
rightButton = ButtonNode(frame: CGRect(x: rightX, y: y, width: width, height: height), agree: false)
leftButton?.addTarget(self, action: #selector(disagreeUsers), for: .touchUpInside)
rightButton?.addTarget(self, action: #selector(agreeUsers), for: .touchUpInside)
view.addSubview(leftButton!)
view.addSubview(rightButton!)
@objc func agreeUsers(){
delegate?.showParticipantsPressed(agree: true)
}
@objc func disagreeUsers(){
delegate?.showParticipantsPressed(agree: false)
}
override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
if(rightButton!.frame.contains(point)) {
return rightButton
}
if(leftButton!.frame.contains(point)){
return leftButton
}
return super.hitTest(point, with: event)
}
【问题讨论】:
-
你需要使用命中测试
-
@RajaKishan 检查更新的代码,命中测试对我不起作用
-
在 hitTest 方法中试试这个 ``` if let hitView = rightButton.hitTest(rightButton.convert(point, from: self), with: event) { return hitView }```
-
@RajaKishan 它有点工作,但表现得很奇怪,有时点击右键会起作用,但左边不会
-
你必须为两者做同样的事情