I have a custom UITableViewCell with static content that has a UIStackView as the single child view of the content view. I would like the UIStackView to use the same horizontal margins/insets as the standard UITableViewCell built into UIKit, across all iOS versions beginning with iOS 9 (my minimum deployment target) down to the current iOS 14, and on both iPhone and iPad devices.
I naively started with adding constraints that attach the UIStackView's leading/trailing anchors to the content view's readableContentGuide
. I don't like Interface Builder so this is how my code looks like:
UIStackView stackView = [...]
[stackView.leadingAnchor constraintEqualToAnchor:self.contentView.readableContentGuide.leadingAnchor].active = YES;
[stackView.trailingAnchor constraintEqualToAnchor:self.contentView.readableContentGuide.trailingAnchor].active = YES;
This works pretty well, except in some scenarios (1) where the standard UITableViewCell does not use readableContentGuide
, so mixing the standard cells with my custom cells looks bad because their edges do not align. Here you see 4 custom cells with one standard cell at the top and at the bottom:
(1) It happens in these scenarios:
- On iPhone devices with a notch, when the device is held in Landscape orientation
- On iPad devices, both in Portrait and Landscape orientation
I have tried using layoutMarginsGuide
instead of readableContentGuide
, but this results in many constraint errors ("Unable to simultaneously satisfy constraints." in Xcode's debug output). I have also tried setting
self.tableView.cellLayoutMarginsFollowReadableWidth = YES;
in table views that use my custom cell, and this works inasmuch as the standard cells now have their edges in the same place as my custom cells. But I don't like the workaround, first because it means I have to have special set up for each and every table view that wants to use my custom cell, and second because it unnecessarily reduces the width available for data display.
It seems I am missing something. Is there a simple, standard way how one can layout the content of a custom UITableViewCell, using layout guides, so that the custom cell content's edges are in the same place as a standard cell's?
question from:
https://stackoverflow.com/questions/65890017/is-there-a-simple-way-how-a-custom-uitableviewcell-can-have-the-same-edges-as-a 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…