在Swift中,我可以使用匿名闭包为变量赋值:
let thumbnailImageView: UIImageView = {
let imageView = UIImageView()
imageView.backGroundColor = UIColor.blueColor()
return imageView;
}
addSubView(thumbnailImageView)
thumbnailImageView.frame = CGRectMake(0,0,100,100)
我试图在Obj-C中做同样的事情,但这会在添加子视图并设置其框架时导致错误:
UIImageView* (^thumbnailImageView)(void) = ^(void){
UIImageView *imageView = [[UIImageView alloc] init];
imageView.backgroundColor = [UIColor blueColor];
return imageView;
};
[self addSubview:thumbnailImageView];
thumbnailImageView.frame = CGRectMake(0, 0, 100, 100);
答案 0 :(得分:0)
您正尝试使用Swift语法编写Objective-C。 Swift示例描述了一个延迟初始化的变量,而Objective-C声明了一个返回UIImageView
的简单块。您需要使用
[self addSubview:thumbnailImageView()];
但是,在这种情况下,使用块来初始化变量毫无意义。如果您正在寻找延迟初始化的属性,它将在Objective-C
中看起来像这样@interface YourClass : Superclass
@property (nonatomic, strong) UIImageView* imageView;
@end
@synthesize imageView = _imageView;
- (UIImageView*)imageView
{
if (!_imageView) {
// init _imageView here
}
return _imageView;
}