简体   繁体   中英

Swift: UIButton vs UIView

In Swift, it appears as though similar behavior can be achieved from a UIButton and a UIView . To give functionality to a button, addTarget can be called, whereas addGestureRecognizer can be called for a UIView . When should one be used over another? In particular, when images are involved, is it better to use a UIButton paired with setImage or UIImageView paired with my_image_view.image = UIImage(...) ?

Additionally, what does a UIButton offer that a UIView doesn't (and vice versa)? Thanks!

The choice is up to you but UIButton is made for if you want a view to be touchable. Moreover, the UIButton class includes every visual effects needed on a button (on press for example). It also has some attribute as selected which can be useful for some uses.

To sum up, if the primary goal of your view is to be clickable, then you should use UIButton .

If the thing you want is a thing you tap and UIButton can be made to work, use it. That way the default accessibility is just correct (for vision impaired users).

If you need features of a UIImageView, but also want to be able to tap it, then use that and add a gesture. You should also consider using the accessibility features to make it possible for vision impaired users to know that you intend the image to be tappable.

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