Swift: UIButton vs. UIView

In Swift, it seems like similar behavior can be achieved with UIButton

and a UIView

. To give functionality to a button, you can call addTarget

, whereas addGestureRecognizer

you can call for UIView

. When should you use the other? In particular when it comes to images, is it better UIButton

to pair with setImage

or UIImageView

pair with my_image_view.image = UIImage(...)

?

Also, what offers UIButton

what UIView

not (and vice versa)? Thank!

+3


source to share


2 answers


The choice is up to you, but UIButton

made for if you want the presentation to be tangible. In addition, the class UIButton

includes all the visual effects required for the button (for example, when pressed). It also has some attribute like selected

, which can be useful for some purposes.



To summarize, if the main purpose of your view is to be interactive, then you should use UIButton

.

+4


source


If the thing you want is the thing you push and the UIButton can be made to work, then use it. So the default accessibility is correct (for visually impaired users).



If you want the features of the UIImageView but also want to be able to use it, use it and add a gesture. You should also consider using accessibility features so that visually impaired users can know that you intend to use the image.

+2


source







All Articles