Creating an autolayout-based metrics view

前端 未结 2 1266
情话喂你
情话喂你 2021-01-05 17:40

I have a reusable view I will be using in UITableViewCell\'s and UICollectionViewCell\'s, and need to get its dimensions for tableView:height

2条回答
  •  独厮守ぢ
    2021-01-05 18:24

    The Autolayout Question

    In the basic case you mentioned, you can get the correct size by calling setNeedsLayout and then layoutIfNeeded on the container view.

    From the UIView class reference on layoutIfNeeded:

    Use this method to force the layout of subviews before drawing. Starting with the receiver, this method traverses upward through the view hierarchy as long as superviews require layout. Then it lays out the entire tree beneath that ancestor. Therefore, calling this method can potentially force the layout of your entire view hierarchy. The UIView implementation of this calls the equivalent CALayer method and so has the same behavior as CALayer.

    I don't think the "entire view hierarchy" applies to your use case since the metrics view presumably wouldn't have a superview.

    Sample Code

    In a sample empty project, with just this code, the correct frame is determined after layoutIfNeeded is called:

    #import "ViewController.h"
    
    @interface ViewController ()
    
    @property (nonatomic, strong) UIView *redView;
    
    @end
    
    @implementation ViewController
    
    @synthesize redView;
    
    - (void)viewDidLoad
    {
        [super viewDidLoad];
        // Do any additional setup after loading the view, typically from a nib.
    
        redView = [[UIView alloc] initWithFrame:CGRectMake(50, 50, 220, 468)];
        redView.backgroundColor = [UIColor redColor];
        redView.translatesAutoresizingMaskIntoConstraints = NO;
        [self.view addSubview:redView];
    
        NSLog(@"Red View frame: %@", NSStringFromCGRect(redView.frame));
        // outputs "Red View frame: {{50, 50}, {220, 468}}"
    
        [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[redView(==100)]" options:0 metrics:Nil views:NSDictionaryOfVariableBindings(redView)]];
        [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-100-[redView(==100)]" options:0 metrics:Nil views:NSDictionaryOfVariableBindings(redView)]];
    
        NSLog(@"Red View frame: %@", NSStringFromCGRect(redView.frame));
        // outputs "Red View frame: {{50, 50}, {220, 468}}"
    
        [self.view setNeedsLayout];
    
        NSLog(@"Red View frame: %@", NSStringFromCGRect(redView.frame));
        // outputs "Red View frame: {{50, 50}, {220, 468}}"
    
        [self.view layoutIfNeeded];
    
        NSLog(@"Red View frame: %@", NSStringFromCGRect(redView.frame));
        // outputs "Red View frame: {{0, 100}, {100, 100}}"
    }
    
    @end
    

    Additional Considerations

    Slightly outside the scope of your question, here are some other issues you may run into, since I've worked on this exact problem in a real app:

    • Calculating this in heightForRowAtIndexPath: might be expensive, so you may want to precalculate and cache the results
    • Precalculation should be done on a background thread, but UIView layout doesn't work well unless it's done on the main thread
    • You should definitely implement estimatedHeightForRowAtIndexPath: to reduce the impact of these performance issues

    Using intrinsicContentSize

    In response to:

    Some subviews have stuff going on inside layoutSubviews so I can't call systemLayoutForContentSize:

    You can use this method if you implement intrinsicContentSize, which lets a view suggest an optimal size for itself. One implementation for this might be:

    - (CGSize) intrinsicContentSize {
        [self layoutSubviews];
        return CGSizeMake(CGRectGetMaxX(self.bottomRightSubview.frame), CGRectGetMaxY(self.bottomRightSubview.frame));
    }
    

    This simple approach will only work if your layoutSubviews method doesn't refer to an already-set size (like self.bounds or self.frame). If it does, you may need to do something like:

    - (CGSize) intrinsicContentSize {
        self.frame = CGRectMake(0, 0, 10000, 10000);
    
        while ([self viewIsWayTooLarge] == YES) {
            self.frame = CGRectInset(self.frame, 100, 100);
            [self layoutSubviews];
        }
    
        return CGSizeMake(CGRectGetMaxX(self.bottomRightSubview.frame), CGRectGetMaxY(self.bottomRightSubview.frame));
    }
    

    Obviously, you'd need to adjust these values to match the particular layout of each view, and you may need to tune for performance.

    Finally, I'll add that due in part to the exponentially increasing cost of using auto-layout, for all but the simplest table cells, I usually wind up using manual height calculation.

提交回复
热议问题