【发布时间】:2013-12-12 17:50:22
【问题描述】:
我正在尝试查看在自定义 UIView 类中初始化 UIIMageViews 的最有效方法,该自定义 UIView 类位于自定义 UITableCell 中
我的自定义视图有多个按钮。本质上,我正在尝试从单元格中复制设置 UIImageviews 的标准方法。我正在尝试的当前方式是懒惰地创建 UIImageview,但 UIImageview 的图像属性为空。如果我第二次调用吸气剂,则不是。
所以在我的表格视图中
- (CustomCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath
*)indexPath {
static NSString *CellIdentifier = @"Cell";
_cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (_cell == nil) {
_cell = [[CustomCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier];
//add link image to cell
_cell.sharingPanel.a_shareButton.image = [UIImage imageNamed:@"button1"];
_cell.sharingPanel.b_shareButton.image = [UIImage imageNamed:@"button2"];
return _cell;
}
在我的自定义视图类中,我有延迟初始化的属性
- (UIImageView *)a_shareButton {
if (!_a_shareButton) {
_a_shareButton = [[UIImageView alloc]init];
_a_shareButton.frame = CGRectMake(0,0,20,40);
[self addSubview:_a_shareButton];
return _a_shareButton;
}
return _a_shareButton;
}
【问题讨论】:
-
抱歉,我不明白问题出在哪里。您的惰性实例化代码看起来不错,我希望 image 属性为零,直到您为其分配一些东西。
-
+1 @JesseRusak 我唯一要补充的是,您不需要在条件中使用
return。你的代码接下来要做的就是返回。 -
您的 tableView 代码中的括号也不平衡,但我猜这是问题中的错字
-
感谢您指出退货声明。我要做的是在 UIImageview 属性上设置 UIImage,该属性位于 UIView 子类中,然后将该视图添加为 UIView 子类的子视图。我试图以与您在 UITableview 单元格中设置单元格的标准图像视图相同的方式执行此操作。我有几个可能设置或未设置的按钮,因此我使用延迟初始化。当我运行上述内容时,它在所述 UIImageview 上设置 UIImage 属性,它不会这样做。是的,这是问题中的错字谢谢!
标签: ios objective-c uiimageview lazy-initialization