Swift 中 override init(frame:CGRect) 的 Obj C 等价物是什么?

What is the Obj C equivalent of override init(frame:CGRect) in Swift?

我是一个尝试在 Obj C 中使用 collectionview 的新手

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 中实现上述 swift 代码。我尝试了以下代码,但未显示子视图。

#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;
} 

这就是任何 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 中的块)是过度的。

您可以做到,但大多数开发人员可能对该代码很感兴趣。 您可以执行以下操作:

- (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 Code Block Evaluation C Extension" 或 "statement expressions"。 关于它有 a question on SO,但由于主要基于意见而被关闭。 正如我所说,这似乎很奇怪。这显然不是 99%(好吧,这是随机统计猜测)iOS 开发人员的第一个代码想法。

本站备注:
不要搜索将 Swift 代码完全复制到 Objective-C 或反向。
虽然所有使用 API 的 CocoaTouch 调用都应该具有相同的逻辑(您可以使用 "translate it without much thinking), each language has it own logic, " 工具”和实现方法。在您的示例中,Objective-C.

中没有任何阻塞