【问题标题】:How to make UIButton clickable outside frame of it's grand parent view如何使 UIButton 在其父视图的框架外可点击
【发布时间】: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 它有点工作,但表现得很奇怪,有时点击右键会起作用,但左边不会
  • 你必须为两者做同样的事情

标签: ios swift uiview uibutton


【解决方案1】:

我遇到了类似的问题,对我有用的是将按钮带到子视图的前面。然后就可以了。

view.bringSubiewToFront(exampleButton)

或将其他子视图发回

view.sendSubViewToBack(viewlayer)

【讨论】:

    猜你喜欢
    • 2014-01-03
    • 1970-01-01
    • 2014-10-07
    • 1970-01-01
    • 1970-01-01
    • 2014-02-15
    • 2012-07-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多