dinosaysrawr
dinosaysrawr

Reputation: 376

Custom view is not clickable after addSubview

View hierarchy before addSubview:

View > TableView

View hierarchy after addSubview:

View > TableView && View > CustomView

After calling addSubview, CustomView is shown on top of TableView as its frame is smaller and it was added after TableView. However, I have buttons and textfields in the CustomView, none of which are working. Even when I tap on the CustomView the TableView's scrollView seems to be capturing the tapGesture. How can I make it so that the CustomView's buttons and textfields to accept touches?

Also, background color of the CustomView is clear, showing the tableView underneath when the customView is added to the view hierarchy. I tried setting background color in the storyboard and programmatically, but it's still stuck at clear. How can I fix this?

class masterViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

//blah blah
@IBOutlet weak var tableView: UITableView! // tableView is added in the storyboard

let newForm = NewFormView(frame: CGRect(x: 0, y: 0, width: 300, height: 300))
    newForm.backgroundColor = UIColor.white
    self.view.addSubview(newForm)
    newForm.translatesAutoresizingMaskIntoConstraints = false
    NSLayoutConstraint.activate([
        newForm.centerXAnchor.constraint(equalTo: self.view.centerXAnchor),
        newForm.centerYAnchor.constraint(equalTo: self.view.centerYAnchor)
        ])
}

newForm is a UIView nib with buttons and textFields added in the nib storyboard

Upvotes: 0

Views: 264

Answers (1)

Shehata Gamal
Shehata Gamal

Reputation: 100523

You need to add width and height constraints

NSLayoutConstraint.activate([
    newForm.centerXAnchor.constraint(equalTo: self.view.centerXAnchor),
    newForm.centerYAnchor.constraint(equalTo: self.view.centerYAnchor),
    newForm.widthAnchor.constraint(equalToConstant:300),
    newForm.heightAnchor.constraint(equalToConstant:300)
])

As when you do

newForm.translatesAutoresizingMaskIntoConstraints = false

your frame becomes invalid and not active in receiving touches

Upvotes: 1

Related Questions