首页 > 解决方案 > UIScrollView 内的 UIViewControllers 内的 UIbutton 在触摸时未触发

问题描述

我在 UIScrollView 中添加了两个 UIViewControllers,现在我正在尝试将目标添加到 UIViewControllers 内的按钮,我已经检查了互联网,但这些解决方案都没有对我有用,这就是我正在做的

在主 ViewController 内部

scrollView.contentSize = CGSize(width: view.frame.width * 2, height:0)

        let postsViewController = PostsViewController()
        postsViewController.scrollView = scrollView
        postsViewController.view.frame = CGRect(x: 0, y: 0, width: view.frame.width, height: view.frame.height)

        let chatsViewController = ChatsViewController()
        chatsViewController.scrollView = scrollView
        chatsViewController.view.frame = CGRect(x: view.frame.width, y: 0, width: view.frame.width, height: view.frame.height)

        scrollView.addSubview(postsViewController.view)
        scrollView.addSubview(chatsViewController.view)

        postsViewController.didMove(toParent: self)
        chatsViewController.didMove(toParent: self)

然后在postsViewController里面我这样做

 let a = UIButton()
    a.setImage(currentTheme.chat, for: .normal)
    a.imageEdgeInsets = UIEdgeInsets(top: 1.5, left: 0.0, bottom: 1.5, right: 0.0)

    view.addSubview(a)
    view.addConstraint("V:|-200-[v0(80)]-0-|",a)
    view.addConstraint("H:|-200-[v0(80)]-0-|",a)

    a.addTarget(self, action: #selector(abc), for: .touchUpInside)

add "addConstraint" 是一个扩展函数,只是为了给视图添加约束

abc 函数

@objc func abc() {
       print("hello")
}

你可以在这里看到scrollView设置

https://ibb.co/ZB1LJsy

标签: iosswift

解决方案


尝试像这样初始化您的按钮

let a : UIButton = UIButton(type: .custom)

并将其添加到您的 UIScrollView 的初始化之后

scrollView.delaysContentTouches = false

推荐阅读