gpt4 book ai didi

ios - 如何在选择器中传递自定义 UITableViewCell

转载 作者:行者123 更新时间:2023-11-28 18:48:27 25 4
gpt4 key购买 nike

我有一个包含 UISwitch 和 UILabel 的自定义 UITableViewCell。轻触开关后,我想知道哪个单元格的开关已激活/停用。

我的 cellForRowAtIndexPathMethod 中有以下代码,用于将目标添加到单元格的 UISwitch:

[cell.notifSwitch addTarget:self action:@selector(switchChangedFromCell:) forControlEvents:UIControlEventValueChanged];

这里是选择器的代码:

- (void)switchChangedFromCell:(id)sender {

HydrationNotificationTableViewCell *cell = (HydrationNotificationTableViewCell *)sender;

if ([cell.notifSwitch isOn]) {
NSLog(@"Notification for %@ has been activated", cell.notifLabel.text);
}

else {
NSLog(@"Deactivated notification %@", cell.notifLabel.text);
}
}

马上我就认为将发送者作为一个单元是错误的,因为发送者实际上是来自单元的 UISwitch。我想知道如何传递单元格本身,以便我知道哪个单元格已更改。

一种解决方案是在我的 cellForRowAtIndexPath 方法中为每个 UISwitch 设置不同的标签,但我想知道是否有更简洁的解决方案。

最佳答案

坏消息是你不能那样做……完全。

好消息是,在您的 IBAction 中,UISwitch 是发送方,您可以使用它来确定哪个单元格包含 UISwitch

我在 Github 上有一个名为 TableViewExtension 的项目这说明了如何去做。

唯一真正的技巧是对 UITableView 的扩展:

public extension UITableView {

/**
This method returns the indexPath of the cell that contains the specified view
- Parameter view: The view to find.
- Returns: The indexPath of the cell containing the view, or nil if it can't be found
*/

func indexPathForView(_ view: UIView) -> IndexPath? {
let origin = view.bounds.origin
let viewOrigin = self.convert(origin, from: view)
let indexPath = self.indexPathForRow(at: viewOrigin)
return indexPath
}
}

如果您添加该扩展,您可以让您的 IBAction 使用发送器来确定哪个控件触发了点击,并调用该方法来确定哪个单元格包含该控件:

@IBAction func controllTriggered(_ sender: UISwitch) {
guard let indexPath = tableView.indexPathForView(sender) else { return }

//Now you have the indexPath of the cell containing `sender`
}

编辑:

请注意,在您的代码中,您试图获取单元格,然后查询单元格的不同 subview 以获取状态数据。不要那样做。您应该将状态数据存储在模型对象中。单元格用于显示信息和与用户交互。

如果用户点击一个开关,IBAction 会将开关作为它的发送器参数。您可以从发送者那里获取 Switch 的值。

关于ios - 如何在选择器中传递自定义 UITableViewCell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46551029/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com