繁体   English   中英

Swift中重写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中实现上述快速代码。 我试过下面的代码,但未显示子视图。

#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中使用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文章。 可以在此处找到 ,并称为“ GCC代码块评估C扩展”或“语句表达式”。 关于SO一个问题 ,但由于主要基于意见而被关闭。 正如我所说,这似乎很奇怪。 显然,这并不是iOS开发人员有99%(好的,这是一个随机的统计猜测)的代码初衷。

网站说明:
不要将Swift代码完全复制到Objective-C或反向搜索。
尽管所有用API进行的CocoaTouch调用都应具有相同的逻辑(您可以“不加思索地进行翻译”),但是每种语言都有其自己的逻辑,“工具”和实现方式。在您的示例中,Objective-C中没有任何障碍。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM