• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

ios - 从自定义 UITableViewCell 和 UIViewController 传递数据

[复制链接]
菜鸟教程小白 发表于 2022-12-12 10:40:27 | 显示全部楼层 |阅读模式 打印 上一主题 下一主题

我(相当)熟悉在 UIViewController 之间传递数据的 segue 和委托(delegate),但我目前的情况略有不同,我无法让它工作。上下文:XCode 5 和 iOS7 与 Objective C。

我有一个表格 View (动态原型(prototype)),它加载包含 UILabel 和 UISwitch 的自定义单元格(来自单独的 nib)。 CustomCell.xib 从 CustomCell.h/m 加载其数据。主要内容在 ViewController.h/m 中,在该文件中,我需要知道开关值是否更改(或者实际上是 UISwitch 的新值)。显然我在 CustomCell.h/m 文件中知道这一点,但需要将它们传递给 ViewController.h/m。

我尝试使用委托(delegate),但我无法为 UINib 实例设置委托(delegate)(与在 View Controller 的实例上设置委托(delegate)相反)。此外,自定义单元格是在 View Controller 中实现的,因此它不会像另一个 View Controller 在导航堆栈中那样被推送。

CustomCell.h

#import <UIKit/UIKit.h>

@protocol CustomCellDelegate <NSObject>

- (void)switchControlValueChangedUISwitch*)switchControl toNewValueBOOL)value;

@end

@interface CustomCell : UITableViewCell

@property (nonatomic, weak) IBOutlet UILabel *titleLabel;
@property (nonatomic, weak) IBOutlet UISwitch *switchControl;
@property (nonatomic, assign) id <CustomCellDelegate> delegate;

- (void)setValueForSwitchControlToBOOL)value;
- (IBAction)changeColorForSwitchControl;

@end

CustomCell.m

- (void)changeColorForSwitchControl // value changed method
{
    ...
    [self.delegate switchControlValueChanged:self.switchControl toNewValue:self.switchControl.on];
}

ViewController.h

#import <UIKit/UIKit.h>
#import "CustomCell.h"

@interface ViewController : UITableViewController <CustomCellDelegate>
...
@end

ViewController.m

- (void)viewDidLoad
{
    ...
    // cannot set a delegate on the cellNib
    UINib *cellNib = [UINib nibWithNibName:kCustomCell bundle:nil];
    [self.tableView registerNib:cellNib forCellReuseIdentifier:kCustomCell];
}

- (void)switchControlValueChangedUISwitch *)switchControl toNewValueBOOL)value
{
    NSLog(@"Switch changed!"); // this is not getting displayed
}



Best Answer-推荐答案


将您的 View Controller 设置为您的单元格的代表的正确时间是在您设置单元格的其他属性时。您可以在 tableView:cellForRowAtIndexPath: 中执行此操作。

- (UITableViewCell *)tableViewUITableView *)tableView cellForRowAtIndexPathNSIndexPath *)indexPath
{
    UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:kCustomCell forIndexPath:indexPath];
    ...
    cell.delegate = self;
    return cell;
}

旁注:registerNib:forCellReuseIdentifier: 完全按照它所说的去做,它只是注册你的 Nib 以供重复使用。在表格 View 决定这样做之前,不会加载 nib 的内容。它会在需要时创建包含在 Nib 中的单元格的副本。

关于ios - 从自定义 UITableViewCell 和 UIViewController 传递数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24587243/

回复

使用道具 举报

懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关注0

粉丝2

帖子830918

发布主题
阅读排行 更多
广告位

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap