首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >UIControl未正确响应

UIControl未正确响应
EN

Stack Overflow用户
提问于 2020-05-10 01:32:27
回答 1查看 43关注 0票数 0

我已经创建了一个自定义的UIControl,其中一个图像和一个标题垂直和水平对齐,一个位于另一个的顶部,应该充当UIButton

问题是,当元素是touch inside时,当我调用addTarget()来添加一个操作时,该操作并不能很好地执行,只有在多次点击之后才能完成工作。

导致此问题的原因是什么?

谢谢。

下面是这个UIControl元素的类。

代码语言:javascript
复制
class CustomImageTitleButton: UIControl {

    private var image : UIImageView = UIImageView()

    private var title : UILabel = UILabel()

    required init?(coder: NSCoder) {
        super.init(coder: coder)

        setup()
    }

    override init(frame: CGRect) {
        super.init(frame: frame)

        setup()
    }

    private func setup() {
        self.backgroundColor = PrimaryLightColor
        self.layer.cornerRadius = 20

        self.translatesAutoresizingMaskIntoConstraints = false
        image.translatesAutoresizingMaskIntoConstraints = false
        title.translatesAutoresizingMaskIntoConstraints = false

        self.addSubview(image)
        self.addSubview(title)

        image.contentMode = .scaleAspectFit

        title.textAlignment = .center
        title.font = title.font.withSize(24)

        setupConstraints()
    }

    private func setupConstraints() {
        NSLayoutConstraint.activate([
            image.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 20),
            image.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -20),
            image.heightAnchor.constraint(equalTo: self.heightAnchor, multiplier: 0.5, constant: 0),
            image.bottomAnchor.constraint(equalTo: self.centerYAnchor, constant: 8),

            title.topAnchor.constraint(equalTo: self.centerYAnchor),
            title.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 4),
            title.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -4),
            title.bottomAnchor.constraint(equalTo: self.bottomAnchor)
        ])
    }

    func setImage(image : UIImage?) {
        self.image.image = image
    }

    func setTitle(title : String?) {
        self.title.text = title
    }
}

下面是该操作的实现:

代码语言:javascript
复制
singlePlayerButton.addTarget(self, action: #selector(initSinglePlayerGame), for: .touchUpInside) // singlePlayerButton is the custom UIControl

@objc func initSinglePlayerGame() {
        print("single player tapped")
        let gameRoom : GameViewController =  GameViewController()
        gameRoom.modalPresentationStyle = .fullScreen
        self.present(gameRoom, animated: true, completion: nil)
    }

编辑:

它看起来像UIControl管理用户交互,但不是一个简单的点击,它更像是一个“点击,拖动和释放”的动作。

EN

回答 1

Stack Overflow用户

发布于 2020-05-10 03:14:21

您可以使用HitTest来确定UI控件的事件处理。

此外,如果UIControl位于视图层次结构的顶部,则可以检查UI视图层次结构。

调试捕获视图调试-> ->视图层次结构

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61700964

复制
相关文章

相似问题

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