UIViewController with custom UIView (that includes a button) doesn't recognize taps

Brendan McLaughlin

When trying to load a custom UIView (BaseHeader.swift) that contains a UIButton into a UIViewController (ViewController.swift) programmatically, the taps on the button are not recognized.

If I extract the code within the custom UIView and paste it directly into the UIViewController, all taps are recognized and working as expected. What am I missing?

At first, I thought it was a problem with not defining a frame size for the UIView after it gets instantiated. I thought that there might be no "hit box" for the button despite it being displayed as intended. After giving the view a frame I still had no luck and tried various other things after googling about for awhile.

The view loads but button taps are not recognized -- see image

ViewController.swift

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        self.title = "Authentication"
    }

    override func loadView() {
        super.loadView()

        let header = BaseHeader()
        header.translatesAutoresizingMaskIntoConstraints = false
        self.view.addSubview(header)

        NSLayoutConstraint.activate([
            header.leadingAnchor.constraint(equalTo: self.view.leadingAnchor),
            header.trailingAnchor.constraint(equalTo: self.view.trailingAnchor),
            header.topAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.topAnchor, constant: -10),
        ])
    }
}

BaseHeader.swift

import UIKit

class BaseHeader: UIView {

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

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

    func setupView() {

        self.isUserInteractionEnabled = true

        let avenirFont = UIFont(name: "Avenir", size: 40)
        let lightAvenirTitle = avenirFont?.light

        let title = UILabel()
        title.text = "Title"
        title.font = lightAvenirTitle
        title.textColor = .black
        title.translatesAutoresizingMaskIntoConstraints = false
        self.addSubview(title)

        NSLayoutConstraint.activate([
            title.topAnchor.constraint(equalTo: self.topAnchor, constant: 20),
            title.centerXAnchor.constraint(equalTo: self.centerXAnchor)
        ])


        let profile = UIButton()
        let profileImage = UIImage(named: "person-icon")
        profile.setImage(profileImage, for: .normal)
        profile.setImage(UIImage(named: "think-icon"), for: .highlighted)
        profile.addTarget(self, action: #selector(profileTapped), for: .touchUpInside)
        profile.backgroundColor = .systemBlue
        profile.frame.size = CGSize(width: 30, height: 30)
        profile.isUserInteractionEnabled = true
        profile.translatesAutoresizingMaskIntoConstraints = false
        self.addSubview(profile)

        NSLayoutConstraint.activate([
            profile.centerYAnchor.constraint(equalTo: title.centerYAnchor),
            profile.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -20),
        ])
    }

    @objc func profileTapped(sender: UIButton) {
        print("Tapped")
    }
}
Giang

You forgot set height for BaseHeader

 NSLayoutConstraint.activate([
            header.leadingAnchor.constraint(equalTo: self.view.leadingAnchor),
            header.trailingAnchor.constraint(equalTo: self.view.trailingAnchor),
            header.topAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.topAnchor, constant: -10),
header.heightAnchor.constraint(equalToConstant: 40) //add more
        ])

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

UIView doesn't add to UIViewController

UIView added as an UIWindow subview doesn't respond to taps

Custom UIView for an UIViewController in Swift

Action of UIButton doesn't work if the button is initialized with let and the addTarget in it in custom view, but it works in UIViewController

SonarQube doesn't recognize custom PomCheck rule

UITapGestureRecognizer in custom UIView doesn't work

UIView snapshots on custom UIViewController transitions

Button control doesn't respond to taps in Swifty `Player` package view controller

Angular 4, custom ErrorHandler doesn't recognize custom Error

Segmented Picker with onTapGesture doesn't respond to taps

iAd shows but doesn't react to taps

Submit POST form when rvest doesn't recognize submit button

Windows UI Automation doesn't recognize button controls

Button in tableViewheader doesn't recognize header no. 0

Custom widget js doesn't recognize template from qweb

Cmake doesn't recognize custom command as valid source

Django doesn't recognize my custom update method in a serializer

Wordpress doesn't recognize the custom post type and taxonomy?

Passing data from UIViewController to Custom UIView with XIB

Initialization of a custom UIView in a UIViewController using a storyboard

Lightswitch: Custom button doesn't call method

Flutter - Custom back button doesn't work

Draw method doesn't get called from the custom UIView

Keyboard doesn't receive taps after app has been in the background

Windows doesn't recognize the GPU

Doesn't recognize flutter image

vuex doesn't recognize the mutation

summarise() doesn't recognize a variable

CMD: doesn't recognize the path

TOP Ranking

  1. 1

    Failed to listen on localhost:8000 (reason: Cannot assign requested address)

  2. 2

    pump.io port in URL

  3. 3

    How to import an asset in swift using Bundle.main.path() in a react-native native module

  4. 4

    Loopback Error: connect ECONNREFUSED 127.0.0.1:3306 (MAMP)

  5. 5

    Compiler error CS0246 (type or namespace not found) on using Ninject in ASP.NET vNext

  6. 6

    BigQuery - concatenate ignoring NULL

  7. 7

    Spring Boot JPA PostgreSQL Web App - Internal Authentication Error

  8. 8

    ggplotly no applicable method for 'plotly_build' applied to an object of class "NULL" if statements

  9. 9

    ngClass error (Can't bind ngClass since it isn't a known property of div) in Angular 11.0.3

  10. 10

    How to remove the extra space from right in a webview?

  11. 11

    Change dd-mm-yyyy date format of dataframe date column to yyyy-mm-dd

  12. 12

    Jquery different data trapped from direct mousedown event and simulation via $(this).trigger('mousedown');

  13. 13

    maven-jaxb2-plugin cannot generate classes due to two declarations cause a collision in ObjectFactory class

  14. 14

    java.lang.NullPointerException: Cannot read the array length because "<local3>" is null

  15. 15

    How to use merge windows unallocated space into Ubuntu using GParted?

  16. 16

    flutter: dropdown item programmatically unselect problem

  17. 17

    Pandas - check if dataframe has negative value in any column

  18. 18

    Nuget add packages gives access denied errors

  19. 19

    Can't pre-populate phone number and message body in SMS link on iPhones when SMS app is not running in the background

  20. 20

    Generate random UUIDv4 with Elm

  21. 21

    Client secret not provided in request error with Keycloak

HotTag

Archive