Objective-C下Storyboard使用自定义UITableViewCell实现控件赋值咨询
自定义UITableViewCell内容赋值实现方案(Objective-C)
1. 先完成自定义Cell类的属性绑定
你之前的属性是定义在customcellnow类中的,所以IBOutlet要绑定到该类本身,不能绑定到主控制器,这是Xcode提示无法绑定的核心原因。
customcellnow.h 示例代码
#import <UIKit/UIKit.h> @interface customcellnow : UITableViewCell // 三个属性均需要加IBOutlet关键字,用于和Storyboard控件绑定 @property (nonatomic, weak) IBOutlet UILabel *labelup; @property (nonatomic, weak) IBOutlet UILabel *labeldown; @property (nonatomic, weak) IBOutlet UIImageView *labelimage; @end
小提示:Xcode 后续版本已自动实现属性的
@synthesize,你已手动写的synthesize代码不需要删除,不影响功能。
2. 主控制器中cellForRowAtIndexPath 实现代码
首先在ViewController.m顶部导入自定义Cell的头文件:
#import "ViewController.h" #import "customcellnow.h" // 导入自定义Cell头文件 @implementation ViewController // 其他已有代码省略 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { // 此处的复用标识需要和你在Storyboard中给customcellnow设置的Reuse Identifier完全一致 static NSString *cellID = @"CustomCellIdentifier"; // 复用Cell customcellnow *cell = [tableView dequeueReusableCellWithIdentifier:cellID forIndexPath:indexPath]; if (!cell) { cell = [[customcellnow alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID]; } // 给两个Label赋值,这里的内容可以替换为你自己的数据源数组对应index的值 cell.labelup.text = [NSString stringWithFormat:@"上标签内容%ld", indexPath.row]; cell.labeldown.text = [NSString stringWithFormat:@"下标签内容%ld", indexPath.row]; // UIImageView赋值实现 // 1. 加载本地图片示例(图片需要放入Assets.xcassets中) cell.labelimage.image = [UIImage imageNamed:@"你的本地图片名称"]; // 2. 如果是NSData转UIImage示例(比如本地沙盒读取、网络下载得到的NSData) // NSData *imageData = [NSData dataWithContentsOfFile:@"沙盒图片路径"]; // cell.labelimage.image = [UIImage imageWithData:imageData]; return cell; } @end
注意事项
- Storyboard中选中customcellnow后,必须在右侧属性检查器中设置Reuse Identifier为和代码中一致的字符串,本示例中为
CustomCellIdentifier - 绑定IBOutlet时,要确保是在customcellnow类的编辑状态下连线,连线目标是customcellnow类的对应属性
- 如果要设置圆角、边框等控件样式,可以在customcellnow的
- (void)awakeFromNib方法中实现,避免复用时重复渲染
内容的提问来源于stack exchange,提问作者stefanosn
相关产品推荐
相关产品推荐

