【问题标题】:Open Camera from within UITableView Cell从 UITableView Cell 中打开相机
【发布时间】:2013-05-31 13:10:35
【问题描述】:

我在自定义单元格中有一个用于 TableView 的按钮,它应该打开相机拍照。

我想到了两种方法,但无法让它们发挥作用。 第一个是从单元格内打开 UIImagePickerController 的一个实例。嗯,好像不能打电话了

[self presentViewController...];

来自单元格内。是这样吗?

由于这个“结果”,我想到将打开 UIImagePickerController 的方法放在 TableViewController 中,然后通过类似的方式从单元格(按钮所在的位置)中调用此方法

[super openCamera];

或者使 TableViewController 成为单元格的委托,使其能够调用方法。

这些想法是否朝着正确的方向发展?你会推荐什么?非常感谢!

【问题讨论】:

    标签: ios uitableview uiimagepickercontroller


    【解决方案1】:

    好的,我想出了一些办法,但我仍然想知道是否可以更轻松地完成它。 这是我找到的解决方案:

    在我添加的自定义单元格中

    @property (nonatomic, assign) id adminController;
    

    然后在 tableViewController 中我自定义了以下方法以使用我创建的自定义单元格并将 tableViewController 设置为“admin”

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        static NSString *CellIdentifier = @"cell";
        CreateCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    
        // Configure the cell...
        cell.adminController = self;
    
        return cell;
    }
    

    所以我终于可以打电话了

    [self.adminController performSelector:@selector(openCamera)];
    

    【讨论】:

    • 这一行的写法[self.adminController performSelector:@selector(openCamera)]; ??
    【解决方案2】:

    这是一个老问题,但我也想回答我的老问题......是的,有一个更简单的方法使用块:

    首先,在你的 UITableViewCell 接口中声明一个公共方法:

    @interface YourCell : UITableViewCell
    
    @property (weak, nonatomic) IBOutlet UIButton *button;
    
    - (void)setDidTapButtonBlock:(void (^)(id sender))didTapButtonBlock;
    
    @end
    

    在 UITableViewCell 子类实现文件中声明一个带有复制属性的私有属性。

    #import "YourCell.h"
    
    @interface YourCell ()
    
    @property (copy, nonatomic) void (^buttonTappedBlock)(id sender);
    
    @end
    

    在UITableViewCell构造函数中添加UIControl的target和action,并实现selector方法

    - (void)awakeFromNib {
        [super awakeFromNib];
    
        [self.button addTarget:self 
                        action:@selector(didTapButton:)  
              forControlEvents:UIControlEventTouchUpInside];
    }
    
    - (void)didTapButton:(id)sender {
        if (buttonTappedBlock) {
            buttonTappedBlock(sender);
        }
    }
    

    最后在控制器中实现tableView:cellForRowAtIndexPath:方法中的block代码

    - (UITableViewCell *)tableView:(UITableView *)tableView 
             cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
        YourCell *cell = (YourCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier 
                                     forIndexPath:indexPath];
    
        [cell buttonTappedBlock:^(id sender) {
            NSLog(@"%@", item[@"title"]);
        }];
    
        return cell;
    }
    

    更多区块信息,可以阅读Working With Blocks

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-12-26
      • 2017-05-24
      • 2012-12-08
      • 1970-01-01
      • 2022-01-24
      • 2017-05-24
      相关资源
      最近更新 更多