UITableView - 嵌入自定义 UITableViewCell 的控件/IBActions class
UITableView - controls / IBActions embedded in custom UITableViewCell class
我想要一个 table 和自定义 UITableViewCell
class 作为行。在每一行(自定义 UITableViewCell
)中,我都有一个控件,用户可以使用该控件更改该行中某些内容的状态。
举个例子,每个 table 行(自定义 UITableViewCell
)包含一个按钮和一个标签,我希望单击按钮将标签文本从 "activated" 到 "deactivated" 来回。
*NOTE** 我理解对于上面的场景我可以使用didSelectRowAtIndexPath
的方式来实现,但这对我的实际使用场景来说是行不通的。我使用上面的场景是因为它更简单,并且包含我需要的核心功能。
通常,如果这不在 UITableViewCell
中,我会有一个带有 IBAction
到 UIViewController
自定义 class 的按钮,以及一个 IBOutlet
到标签。 IBAction
方法会更改 IBOutlet
标签的文本。相当标准的东西。
但是由于控件嵌入在 table 行中,我无法建立 IBAction
连接。我已经尝试与 UIViewController
以及 UITableViewCell
建立 IBAction
连接,但它似乎不允许这样做。我应该如何设置它?在我看来,这在界面设计中是一件非常有用的事情,所以我认为这应该是可能的吧?
您可以在 cellForRowAtIndexPath
中设置按钮的操作,如下所示:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! YourCustomCell
cell.button.addTarget(self, action: "buttonClicked:", forControlEvents: UIControlEvents.TouchUpInside)
return cell
}
func buttonClicked(button: UIButton) {
// get row index
let index = self.tableView.indexPathsForRowsInRect(button.superview!.convertRect(button.frame, toView: self.tableView))
}
首先,我可以控制从 UITableViewCell xib 中的按钮拖动到我的头文件以创建 IBAction。您只需选择从 Outlet 到 Action 的连接。
另一方面,您可以通过代码指定按钮的操作。
如果您的按钮是 属性,假设它是 self.tableCellButton,添加如下操作:
[self.tableCellButton addTarget:self action:@selector(yourAction:) forControlEvents:UIControlEventTouchUpInside];
我想要一个 table 和自定义 UITableViewCell
class 作为行。在每一行(自定义 UITableViewCell
)中,我都有一个控件,用户可以使用该控件更改该行中某些内容的状态。
举个例子,每个 table 行(自定义 UITableViewCell
)包含一个按钮和一个标签,我希望单击按钮将标签文本从 "activated" 到 "deactivated" 来回。
*NOTE** 我理解对于上面的场景我可以使用didSelectRowAtIndexPath
的方式来实现,但这对我的实际使用场景来说是行不通的。我使用上面的场景是因为它更简单,并且包含我需要的核心功能。
通常,如果这不在 UITableViewCell
中,我会有一个带有 IBAction
到 UIViewController
自定义 class 的按钮,以及一个 IBOutlet
到标签。 IBAction
方法会更改 IBOutlet
标签的文本。相当标准的东西。
但是由于控件嵌入在 table 行中,我无法建立 IBAction
连接。我已经尝试与 UIViewController
以及 UITableViewCell
建立 IBAction
连接,但它似乎不允许这样做。我应该如何设置它?在我看来,这在界面设计中是一件非常有用的事情,所以我认为这应该是可能的吧?
您可以在 cellForRowAtIndexPath
中设置按钮的操作,如下所示:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! YourCustomCell
cell.button.addTarget(self, action: "buttonClicked:", forControlEvents: UIControlEvents.TouchUpInside)
return cell
}
func buttonClicked(button: UIButton) {
// get row index
let index = self.tableView.indexPathsForRowsInRect(button.superview!.convertRect(button.frame, toView: self.tableView))
}
首先,我可以控制从 UITableViewCell xib 中的按钮拖动到我的头文件以创建 IBAction。您只需选择从 Outlet 到 Action 的连接。
另一方面,您可以通过代码指定按钮的操作。
如果您的按钮是 属性,假设它是 self.tableCellButton,添加如下操作:
[self.tableCellButton addTarget:self action:@selector(yourAction:) forControlEvents:UIControlEventTouchUpInside];