自定义UITableViewCell editingAccessoryView?
这里的困境:我想创build一个自定义的editingAccessoryView
,其中包含我的股票UITableViewCell
两个button。 我想用故事板实现这一点。 到目前为止,我已经按照这里和这里列出的步骤进行了操作。 我似乎无法得到它的工作。 我得到的最接近的是当我创build一个UIView
types的xib,设置类为我的UIViewController
包含UITableView
绑定到我的IBOutlet
,但在cellForRowAtIndexPath
它是nil
。
事实是,我想我只需要知道如何创build视图,然后将其映射到editAccessoryView
; 从那里我相信我可以弄清楚如何添加button并映射相应的IBAction
。 任何人都可以提供一些分步说明或指导教程的链接?
我用下面的代码自己解决了这个问题:
UIView *editingCategoryAccessoryView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 120, 35)]; UIButton *addCategoryButton = [UIButton buttonWithType:UIButtonTypeRoundedRect]; [addCategoryButton setTitle:@"Add" forState:UIControlStateNormal]; [addCategoryButton setFrame:CGRectMake(0, 0, 50, 35)]; [addCategoryButton addTarget:self action:@selector(addCategoryClicked:withEvent:) forControlEvents:UIControlEventTouchUpInside]; UIButton *removeCategoryButton = [UIButton buttonWithType:UIButtonTypeRoundedRect]; [removeCategoryButton setTitle:@"Remove" forState:UIControlStateNormal]; [removeCategoryButton setFrame:CGRectMake(55, 0, 65, 35)]; [removeCategoryButton addTarget:self action:@selector(removeCategoryClicked:withEvent:) forControlEvents:UIControlEventTouchUpInside]; [editingCategoryAccessoryView addSubview:addCategoryButton]; [editingCategoryAccessoryView addSubview:removeCategoryButton]; cell.editingAccessoryView = editingCategoryAccessoryView;
正如你所看到的,我通过编程创build了一个新的UIView
并通过addSubview
添加了两个button,然后将其分配给了editingAccessoryView
。
我知道这可能来不及帮助,但它比你find的解决scheme好得多。 iOS为您提供了一个名为tableView: editActionsForRowAtIndexPath indexPath:
。 这个方法基本上允许你添加你自己的UITableViewRowActions,这比用UIButtons添加整个UIView更容易(也更干净)。
苹果说:
当您想要为其中一个表格行提供自定义操作时使用此方法。 当用户在一行中水平滑动时,表视图将行内容移到一边以显示您的操作。 点击其中一个动作button执行与动作对象一起存储的处理程序块。
如果不实现此方法,则表格视图在用户滑动行时显示标准附件button。
如果你愿意的话,你可以自己看一下Apple的文档 。
示例(Swift)
override func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [AnyObject]? { let customAction = UITableViewRowAction(style: .Normal, title: "Your Custom Action", handler: { (action: UITableViewRowAction!, indexPath: NSIndexPath!) in println("Do whatever it is you want to do when they press your custom action button") }) editAction.backgroundColor = UIColor.greenColor() let deleteAction = UITableViewRowAction(style: .Normal, title: "Delete", handler: { (action: UITableViewRowAction!, indexPath: NSIndexPath!) in println("You can even implement a deletion action here") }) deleteAction.backgroundColor = UIColor.redColor() return [deleteAction, editAction] }