首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >为什么没有调用touchesBegan侦听器(Swift 4)?

为什么没有调用touchesBegan侦听器(Swift 4)?
EN

Stack Overflow用户
提问于 2018-01-28 12:37:17
回答 1查看 946关注 0票数 0

我创建了简单的按钮- class Btn: UIControl,然后添加到父视图。在我的Btn类中,我有override func touchesBegan。当我点击按钮时,为什么touchesBegan不打电话呢?正如我想的那样,我的Btn扩展了UIControlBtn不得不调用touchesBegan

我的代码:

导入UIKit

代码语言:javascript
运行
复制
class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

//        add my button
        let button = Btn()
        view.addSubview(button)
    }
}

class Btn: UIControl {
    fileprivate let button: UIButton = {
        let swapButton = UIButton()
        let size = CGFloat(50)
        swapButton.frame.size = CGSize(width: size, height: size)
        swapButton.backgroundColor = UIColor.green

        return swapButton
    }()

    override init(frame: CGRect) {
        super.init(frame: frame)
        addSubview(button)
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        addSubview(button)
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesBegan(touches, with: event)

        //        Why it not called?
        print("test")
    }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-01-28 13:04:22

根据您的代码,使用下面的操场代码,您将了解正在发生的事情。当您的控件想要处理touchesBegan回调时,它的内部有一个UIButton,它会消耗事件本身。在下面的示例中,内部按钮是Btn大小的四分之一(红色部分),如果单击它,“测试”文本将不会被打印出来。Btn空间的其余部分(绿色部分)不包含将消耗touchesBegan的任何其他视图,因此单击那里将打印"test“文本。

我建议你看看应答链

代码语言:javascript
运行
复制
import PlaygroundSupport
import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        //        add my button
        let button = Btn(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
        view.addSubview(button)
    }
}

class Btn: UIControl {
    fileprivate let button: UIButton = {
        let swapButton = UIButton()
        let size = CGFloat(50)
        swapButton.frame.size = CGSize(width: size, height: size)
        swapButton.backgroundColor = UIColor.green

        return swapButton
    }()

    override init(frame: CGRect) {
        super.init(frame: frame)
        addSubview(button)
        self.backgroundColor = .red
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        addSubview(button)
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesBegan(touches, with: event)

        //        Why it not called?
        print("test")
    }
}
// Present the view controller in the Live View window
PlaygroundPage.current.liveView = ViewController()
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48486432

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档