简体   繁体   中英

Determine location of UITableViewCell's accessory view

I have a UITableView with cells that contain a standard disclosure accessory view. The cell itself isn't too interesting. It's in a Storyboard, using AutoLayout. There's a right-aligned label. I also have a section header, with labels corresponding to the cells' labels. See attached image, from an iPhone 7+.

节标题和两个单元格

I'd like to get the section header labels (specifically the horizontal bar) aligned with the cell labels. The trouble is the cell accessory view, with doesn't have a guaranteed location, and said location will vary based on device. The existing layout is perfect for an iPhone 7, but as you can see in the image the bars are out of alignment due to the accessory view being a bit further to the left on the 7 Plus.

What I'd like to do is figure out where the accessory view lands, and adjust the section header accordingly. I'd like to do it without messy hacks - I like my code clean whenever possible. I'm hoping there's an OS constant or method I'm just not aware of, or a known proportion for determining accessory view position that never changes.

I've run into this before, and solved it various ways that I'd like to improve upon. Things I'd like to avoid:

  • Get the tableView width and if it's an iPhone 7 Plus move everything by a constant number of pixels. Clean and predictable, until a new OS or device width breaks the expected location.
  • Use a UITableViewCell for the section header, including an accessory view in the section header, finding the accessory view at runtime, and setting it to alpha=0 (or just removing the accessory image). I've done this in cells where I needed similar alignment (some cells with accessories and some without). I throw up in my mouth a little just thinking about it.
  • Get the cell's rightmost label location after layout, and send that location to the section header, who will use it to update label locations (by adjusting an Auto Layout Constraint). It should work but the messy messaging goes against my "clean code" desire.

So I'm curious as to other ways to solve this, hopefully clean ways, but even ways I've just not thought about. Thanks!

I think the easiest and less messier way to solve this would be creating completely custom cells and header view. If you create yourself the layout for these cells and header, you will be able to have complete control over it - you can design it exactly the way they are right now, but with the right constraints you can garantee the position each view will be and adjust the position, if really necessary.

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