简体   繁体   中英

How do I center images in UITableViewCells programmatically?

I would like my iOS app to display images in every prototype UITableViewCell in the UITableView . My UITableView has been created in a Storyboard and the image is specified programmatically with the imageView property, not with NSLayoutConstraints and Auto Layout.

I found that the alignment of the UIImages varies from the widths of the icons. For instance, in the following image there are two blue icons which have a different width. The second icon with the UILabel next to it seems to be not properly aligned if compared to the other row at the top:

I guess this misplacement can be fixed by using Auto Layout by placing an image in the prototype cell, and then setting up constraints for every icon. I think this is tedious work and there should be a better way because the imageView property really comes in handy in this case. It doses almost the job for you. Probably a property to center the image so even if images in cells don't have equal widths it all looks fine.

Once you get to understand Constraints, they're not that bad, and cells are one of the simplest cases to configure.

In this case, just set a constraint on the width (ie, set the width to be XX), another constraint to centre it vertically within the cell, and then a couple constraints on the label next to the image (left and right).

One of the reasons that constraints are becoming so important is because of the varying widths of screens (and hence, cells in tableviews) so to get them looking right, constraints do make it much easier.

You can set the content mode on the UIImageView. Try the centre option.

imageView.contentMode = .center

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