我是在Obj C尝试收藏的新手
override init(frame:CGRect){
super.init(frame:frame)
let thumbnailImageView: UIImageView = {
let imageView = UIImageView()
imageView.backGroundColor = UIColor.blueColor()
return imageView;
}
addSubView(thumbnailImageView)
thumbnailImageView.frame = CGRectMake(0,0,100,100)
}
我想在Obj C中实现上面的快速代码。我试过下面的代码,但子视图没有显示。
#import "VideoCell.h"
@implementation VideoCell
- (instancetype) initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
UIImageView * thumbnailImageView = [[UIImageView alloc] init];
thumbnailImageView.backgroundColor = [UIColor greenColor];
thumbnailImageView.frame = CGRectMake(0, 0, 100, 100);
[self addSubview:thumbnailImageView];
}
return self;
}
答案 0 :(得分:1)
这就是任何Objective-C开发人员所做的事情:
- (instancetype) initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
UIImageView * thumbnailImageView = [[UIImageView alloc] init];
thumbnailImageView.backgroundColor = [UIColor greenColor];
thumbnailImageView.frame = CGRectMake(0, 0, 100, 100);
[self addSubview:thumbnailImageView];
}
return self;
}
在您的示例中使用闭包(或Objective-C中的Block)过度使用。
您可以这样做,但大多数开发人员可能会对该代码感兴趣。 您可以这样做:
- (instancetype) initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
UIImageView *imageView = ({
UIImageView *imgV = [[UIImageView alloc] init];
imgV.backgroundColor = [UIColor greenColor];
imgV;
});
[self.view addSubview:imageView];
imageView.frame = CGRectMake(0, 0, 100, 100);
}
return self;
}
这取自NSHipster文章。 它可以找到there,称为“GCC代码块评估C扩展”或“语句表达式”。 关于它有a question on SO,但由于主要基于意见而被关闭。 正如我所说,这似乎很奇怪。这显然不是代码的第一个想法99%(好吧,这是一个随机的统计猜测)iOS开发人员会有。
网站注意:
不要搜索将Swift代码完全复制到Objective-C或反向
虽然所有使用API的CocoaTouch调用应该具有相同的逻辑(在那里你可以“不经过深思熟虑地翻译它”),但每种语言都有自己的逻辑,“工具”和方法。在你的例子中,Objective-C中没有块。