【问题标题】:lazy instantiation UIImageView惰性实例化 UIImageView
【发布时间】: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


【解决方案1】:

不确定这是不是最好的处理方式,但我在我的分享按钮 UIImagview 的图像属性上使用了 KVO。更新后,在 uiview 自定义类中,我正在更新 UIImageview 的 frame 属性

- (UIImageView *)a_shareButton {

if (!_a_shareButton) {
    _a_shareButton = [[UIImageView alloc]init];
    _a_shareButton.uiTag = A_BUTTON;
    [self addSubview:_a_shareButton];
 }
  return _a_shareButton;
}


 - (id)initWithFrame:(CGRect)frame
{
  self = [super initWithFrame:frame];
  if (self) {
    [self addObserver:self
                   forKeyPath:@"a_shareButton.image"
                      options:0 context:nil];
    }
  return self;
  }

   - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary  
   *)change context:(void *)context {

    _a_shareButton.frame = CGRectMake(0, 0,          
    _a_shareButton.image.size.width, _a_shareButton.image.size.height);

   }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-26
    • 2012-01-19
    相关资源
    最近更新 更多