Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
330 views
in Technique[技术] by (71.8m points)

ios - Offscreen UITableViewCells (for size calculations) not respecting size class?

I am using Auto Layout and size classes inside a UITableView with cells that self-size based on their content. For this I'm using the method where for each type of cell, you keep an offscreen instance of that cell around and use systemLayoutSizeFittingSize on that to determine the correct row height - this method is explained wonderfully in this StackOverflow post and elsewhere.

This worked great until I started using size classes. Specifically I've defined different constants on the margin constraints for text in Regular Width layouts, so there is more whitespace around the text on iPad. This gives me the following results.

before and after

It appears that the new set of constraints is being honored (there is more whitespace), but that the row height calculation still returns the same value as it would for a cell that didn't apply the size class-specific constraints. Some part of the layout process in the offscreen cell is not taking the window's size class into account.

Now I figured that that's probably because the offscreen view has no superview or window, and as such it doesn't have any size class traits to refer to at the point the systemLayoutSizeFittingSize call occurs (even though it does seem to use the adjusted constraints for the margins). I now work around this by adding the offscreen sizing cell as a subview of the UIWindow after it's created, which gives the desired result:

fixed

Here's what I'm doing in code:

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    let contentItem = content[indexPath.item]

    if let contentType = contentItem["type"] {
        // Get or create the cached layout cell for this cell type.
        if layoutCellCache.indexForKey(contentType) == nil {
            if let cellIdentifier = CellIdentifiers[contentType] {
                if var cachedLayoutCell = dequeueReusableCellWithIdentifier(cellIdentifier) as? UITableViewCell {                        
                    UIApplication.sharedApplication().keyWindow?.addSubview(cachedLayoutCell)
                    cachedLayoutCell.hidden = true
                    layoutCellCache[contentType] = cachedLayoutCell
                }
            }
        }

        if let cachedLayoutCell = layoutCellCache[contentType] {
            // Configure the layout cell with the requested cell's content.
            configureCell(cachedLayoutCell, withContentItem: contentItem)

            // Perform layout on the cached cell and determine best fitting content height.
            cachedLayoutCell.bounds = CGRectMake(0.0, 0.0, CGRectGetWidth(tableView.bounds), 0);
            cachedLayoutCell.setNeedsLayout()
            cachedLayoutCell.layoutIfNeeded()

            return cachedLayoutCell.contentView.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize).height
        }
    }

    fatalError("not enough information to determine cell height for item (indexPath.item).")
    return 0
}

Adding views to the window that aren't ever supposed to be drawn seems like a hack to me. Is there a way to have UIViews fully adopt the window's size class even when they're not currently in the view hierarchy? Or is there something else I'm missing? Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Update on Dec 2015:

Apple now discourages overriding -traitCollection. Please consider using other workarounds. From the doc:

IMPORTANT

Use the traitCollection property directly. Do not override it. Do not provide a custom implementation.


Original Answer:

The existing answer is great. It explained that the problem is that:

The proposed workaround is to temporarily add the cell to the table view. However, this does NOT work if we are in, say, -viewDidLoad, in which the traitCollection of the table view, or the view of the view controller, or even the view controller itself, is not valid yet.

Here, I propose another workaround, which is to override traitCollection of the cell. To do so:

  1. Create a custom subclass of UITableViewCell for the cell (which you probably did already).

  2. In the custom subclass, add a - (UITraitCollection *)traitCollection method, which overrides the getter of the traitCollection property. Now, you can return any valid UITraitCollection you like. Here's a sample implementation:

    // Override getter of traitCollection property
    // https://stackoverflow.com/a/28514006/1402846
    - (UITraitCollection *)traitCollection
    {
        // Return original value if valid.
        UITraitCollection* originalTraitCollection = [super traitCollection];
        if(originalTraitCollection && originalTraitCollection.userInterfaceIdiom != UIUserInterfaceIdiomUnspecified)
        {
            return originalTraitCollection;
        }
    
        // Return trait collection from UIScreen.
        return [UIScreen mainScreen].traitCollection;
    }
    

    Alternatively, you can return a suitable UITraitCollection created using any one of its create methods, e.g.:

    + (UITraitCollection *)traitCollectionWithDisplayScale:(CGFloat)scale
    + (UITraitCollection *)traitCollectionWithTraitsFromCollections:(NSArray *)traitCollections
    + (UITraitCollection *)traitCollectionWithUserInterfaceIdiom:(UIUserInterfaceIdiom)idiom
    + (UITraitCollection *)traitCollectionWithHorizontalSizeClass:(UIUserInterfaceSizeClass)horizontalSizeClass
    + (UITraitCollection *)traitCollectionWithVerticalSizeClass:(UIUserInterfaceSizeClass)verticalSizeClass
    

    Or, you can even make it more flexible by doing this:

    // Override getter of traitCollection property
    // https://stackoverflow.com/a/28514006/1402846
    - (UITraitCollection *)traitCollection
    {
        // Return overridingTraitCollection if not nil,
        // or [super traitCollection] otherwise.
        // overridingTraitCollection is a writable property
        return self.overridingTraitCollection ?: [super traitCollection];
    }
    

This workaround is compatible with iOS 7 because the traitCollection property is defined in iOS 8+, and so, in iOS 7, no one will call its getter, and thus our overriding method.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...