简体   繁体   中英

UIButton inside UIView inside UIScrollView not firing tap action

I've been looking for this for hours and have no luck yet. I want to use two custom views inside a scrollview. The first view have a button as a subview that leads the user to the next page(scrolls down). But the button action it's never fired. If I use the button as a scrollview subview everything works fine, but that's not what I want.

The code for the scrollview view controller:

    class ViewController: UIViewController {

    @IBOutlet weak var scrollView: UIScrollView!

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        let redView = View1()
        redView.view.frame = CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.scrollView.frame.height)
        self.scrollView.addSubview(redView.view!)

        let blueView = UIView(frame: CGRect(x: 0, y: self.scrollView.frame.height, width: self.view.frame.width, height: self.scrollView.frame.height))
        blueView.backgroundColor = .blue
        self.scrollView.addSubview(blueView)

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

    func go(to page: Int) {
        let y = CGFloat(page) * self.scrollView.frame.size.height
        self.scrollView.setContentOffset(CGPoint(x: 0, y: y), animated: true)
    }
}

ScrollView Storyboard Configuration

The code of the View1 Class:

    class View1: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    @IBAction func didTouchUpInsideMoreInfoButton(_ sender: Any) {
        print("test")
    }
}

Any ideas are welcome. Thanks in advance.

Turn out that I was using a view controller's view and for some reason, the selectors don't work this way. So, what I did was to create a UIView only and then everything works just fine.

  1. Check if the buttons userInteraction is enabled.
  2. Sometimes if your button is inside another view, a UIView for example, it doesn't allow you to tap it. To fix this, you might want to add the button ON TOP of that view but not inside it. Make sure it's above but not inside any view in on your storyboard.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM