Get UIView Height in UITableviewCell Autolayouts

I want to get actual width of UIViewA according to device at cellForRowAtIndexPath method and 'UIViewA' is in custom UITableViewCell. I use AutoLayouts in UITableViewCell.

Please guide me how can I get width of UIView at cellForRowAtIndexPath because I want to add dynamic content in UIView.

3 answers

  • answered 2018-04-17 06:33 Kowboj

    How about that?

    cell.UIViewA.frame.size.width
    

    or

    cell.UIViewA.bounds
    

  • answered 2018-04-17 08:54 Vicky_Vignesh

    Add this to your view creation in the cell

    UIView *backgroundView = [UIView new];
    [backgroundView setTranslatesAutoresizingMaskIntoConstraints:NO];
    [backgroundView setBackgroundColor:[UIColor grayColor]];
    backgroundView.layer.cornerRadius = 5;
    [self addSubview:backgroundView];
    
    
    NSDictionary *viewsDictionary = NSDictionaryOfVariableBindings(backgroundView);
    
    
    [NSLayoutConstraint activateConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[backgroundView]|"
                                                                                    options:0
                                                                                    metrics:nil
                                                                                      views:viewsDictionary]];
    
    [NSLayoutConstraint activateConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[backgroundView]|"
                                                                                    options:0
                                                                                    metrics:nil
                                                                                      views:viewsDictionary]];
    

    Now you can print your view frame and get the width.

  • answered 2018-04-17 13:34 paulvs

    In general, when you need to consult a view's frame or bounds and it is positioned using Autolayout, first do the following:

    [myView setNeedsLayout];
    [myView layoutIfNeeded];
    

    Now myView will have its correct frame and bounds.