我创建了自定义tableView控制器,在单元格内,我已经放置了一个按钮来打开设备照片库.我的问题,我无法从CustomCell.m打开imagePickerController,其显示如下错误.
请给出一些想法来解决我的问题.
解决方法
TableViewCell是一个视图,你不能出现在视图上,而UIViewController可以处理它.您应该将控件从您的单元格传输到您的控制器,该控制器拥有表格视图并为其创建自定义单元格.
尝试这样:
自定义单元格.h类:
@protocol changePictureProtocol <NSObject> -(void)loadNewScreen:(UIViewController *)controller; @end @property (nonatomic,retain) id<changePictureProtocol> delegate;
然后在
将其添加到m文件中:
-(IBAction)changePicture:(id)sender
{
// ..... blah blah
[self.delegate loadNewScreen:picker];
}
加载此单元格的viewcontroller:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// create cell here
cell.delegate = self;
}
-(void)loadNewScreen:(UIViewController *)controller;
{
[self presentViewController:controller animated:YES completion:nil];
}
它是一个psuedocode给你一个想法.
编辑:
Swift等效:
CustomTableViewCell.swift代码:
protocol ChangePictureProtocol : NSObjectProtocol {
func loadNewScreen(controller: UIViewController) -> Void;
}
class CustomTableViewCell: UITableViewCell {
// Rest of the class stuff
weak var delegate: ChangePictureProtocol?
@IBAction func changePicture(sender: AnyObject)->Void
{
var pickerVC = UIImagePickerController();
if((delegate?.respondsToSelector("loadNewScreen:")) != nil)
{
delegate?.loadNewScreen(pickerVC);
}
}
}
ViewController.swift代码:
func tableView(tableView: UITableView,cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
var cell = tableView.dequeueReusableCellWithIdentifier("cellIdentifier") as CustomTableViewCell!
cell.delegate = self;
return cell;
}
func loadNewScreen(controller: UIViewController) {
self.presentViewController(controller,animated: true) { () -> Void in
};
}