Xys
Xys

Reputation: 10789

iOS - Replace a label by a button

I've added a label in a view controller via the interface builder, and I've added a lot of constraints to it, but I want to replace it by a button. Can I accomplish this without losing all the constraints ? Thanks a lot in advance

Upvotes: 0

Views: 127

Answers (3)

Pradeep Singh
Pradeep Singh

Reputation: 160

you don't need to remove that label. Just addGestureRecognizer a tap gesture on label.

let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleTap(_ :)))
myLabel.isUserInteractionEnabled = true
myLabel.addGestureRecognizer(tapGestureRecognizer)


func handleTap(_ sender: UITapGestureRecognizer) {
    // perform some action when the label is tapped
} 

Upvotes: -1

DoesData
DoesData

Reputation: 7047

I'm not sure if you can save your constraints inside interface builder. However, you can add a tap gesture recognizer to make the label perform an action when it is tapped (act like a button).

This code can help you get started:

let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleTap(_ :)))
myLabel.isUserInteractionEnabled = true
myLabel.addGestureRecognizer(tapGestureRecognizer)


func handleTap(_ sender: UITapGestureRecognizer) {
    // perform some action when the label is tapped
}

You can look at this question for more information.

Upvotes: 1

Kathiresan Murugan
Kathiresan Murugan

Reputation: 2962

Don’t replace by button

Add tap gesture for click action

Upvotes: 1

Related Questions