How To Dynamically change the contentSize of UIPopoverController?

后端 未结 8 457
执念已碎
执念已碎 2020-12-14 16:35

I have a UIViewController that contains a UITableView. This UIViewController is being displayed in a UIPopoverController.

相关标签:
8条回答
  • 2020-12-14 17:14

    I was having this same problem and none of the answers I found worked. I cobbled together that I think works well.

    I have an array in my initWithCoder that holds my values. I simply run this code:

    - (id)initWithCoder:(NSCoder *)aDecoder
    {
    //Popover Choices
    
    _importantChoices = [NSMutableArray array];
    [_importantChoices addObject:@"Bakery"];
    [_importantChoices addObject:@"Beverage Dry Mix"];
    [_importantChoices addObject:@"Beverage RTD"];
    [_importantChoices addObject:@"Crisps"];
    [_importantChoices addObject:@"Meat"];
    [_importantChoices addObject:@"Supplements"];
    
    
    //Calculate size of Popover
    self.clearsSelectionOnViewWillAppear = NO;
    NSInteger rowsCount = [_importantChoices count];
    NSInteger singleRowHeight = [self.tableView.delegate tableView:self.tableView
                                           heightForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
    NSInteger totalRowsHeight = rowsCount * singleRowHeight;
    CGFloat largestLabelWidth = 0;
    for (NSString *tmp in _importantChoices) {
        CGSize labelSize = [tmp sizeWithAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:20.0f]}];
        if (labelSize.width > largestLabelWidth) {
            largestLabelWidth = labelSize.width;
        }
    }
    CGFloat popoverWidth = largestLabelWidth + 100;     //Add a little padding to the width
    self.preferredContentSize = CGSizeMake(popoverWidth, totalRowsHeight);
    return self;
    }
    
    0 讨论(0)
  • 2020-12-14 17:17

    Well, In the end i did something that I'm not sure if it's the right thing to do, but it is working.

    I added a reference in my contentViewController to the popoverController:

    @property (nonatomic , assign) UIPopoverController *popoverControllerContainer;
    

    Then, I added the resizing code to viewWillAppear and viewDidAppear:

    - (void)viewDidLoad
    {
        [super viewDidLoad];
        [self.tableView reloadData];
    }
    
    -(void) viewWillAppear:(BOOL)animated
    {
        [super viewWillAppear:animated];
        self.contentSizeForViewInPopover = self.tableView.contentSize;
    }
    
    -(void) viewDidAppear:(BOOL)animated
    {
        [super viewDidAppear:animated];
        [self.popoverControllerContainer setPopoverContentSize:self.contentSizeForViewInPopover animated:YES];
    }
    

    So, keeping a reference to the popover is kind of hack-ish, so I'm open to hear better ideas.

    0 讨论(0)
提交回复
热议问题