天天看点

UIPopoverController详解

今天一位童鞋问我个问题,大意是popoverController不会显示。经过我寻找问题发现下面这个方法不好掌控。为什么说他不好掌控那。我这个给大家带来一个列子,通过这个列子来介绍PopoverController的详细用法,以及这个方法的2中传参技巧。

- (void)presentPopoverFromRect:(CGRect)rect inView:(UIView *)view permittedArrowDirections:(UIPopoverArrowDirection)arrowDirections animated:(BOOL)animated;

方案1:新建一个view,在这个view上添加手势来监听PopoverController的弹出。

监听方法如下:

- (IBAction)tapClick:(UITapGestureRecognizer *)sender {
    ColorViewController *color = [[ColorViewController alloc]init];
    
    _pc = [[UIPopoverController alloc] initWithContentViewController:color];
    _pc.popoverContentSize = CGSizeMake(320, 480);
    
    [_pc presentPopoverFromRect:sender.view.bounds inView:sender.view permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
}
           

请大家仔细看:这里的sender只是一个手势。上面的sender.view是谁?就是手势被添加的视图。fromRect这个传的就是手势被添加的到哪个视图就传哪个视图。后边的inview意思就是popover在哪个视图?当然是在手势被添加的视图了。

方案2:新建一个button,在这个button上添加手势来监听PopoverController的弹出

- (IBAction)btnClick:(UIButton *)sender
{
    ColorTableViewController *color = [[ColorTableViewController alloc]init];
    
    _pc = [[UIPopoverController alloc] initWithContentViewController:color];
    _pc.popoverContentSize = CGSizeMake(320, 480);
    
    [_pc presentPopoverFromRect:sender.bounds inView:sender permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
}
           

这里的sender指的是按钮,fromRect传的是按钮的尺寸,后面的inview传的是按钮本身。道理同上。

3.新建一个controller继承UITableViewController

UIPopoverController详解

4.编写数据源方法

#pragma mark - 数据源方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    return 20;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    cell.textLabel.text = [NSString stringWithFormat:@"第%d行数据",indexPath.row];
    CGFloat red = arc4random_uniform(255) / 255.0;
    CGFloat green = arc4random_uniform(255) / 255.0;
    CGFloat black = arc4random_uniform(255) / 255.0;
    cell.contentView.backgroundColor = [UIColor colorWithRed:red green:green blue:black alpha:1];
    
    return cell;
}

           

5.效果图

UIPopoverController详解
UIPopoverController详解