gpt4 book ai didi

ios - 相当于 override init(frame :CGRect) in Swift?

转载 作者:行者123 更新时间:2023-11-29 00:12:50 26 4
gpt4 key购买 nike

我是一个尝试在 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 代码。我尝试了以下代码,但未显示 subview 。

#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 文章。可以查到there并称为“GCC 代码块评估 C 扩展”或“语句表达式”。有a question on SO关于它,但由于主要基于意见而关闭。正如我所说,这似乎很奇怪。这显然不是 99%(好吧,这是随机统计猜测)的 iOS 开发人员对代码的第一个想法。

站点注释:
不要搜索将 Swift 代码完全复制到 Objective-C 或反向。
虽然所有使用 API 的 CocoaTouch 调用都应该具有相同的逻辑(您可以“无需太多思考就可以翻译它”),但每种语言都有自己的逻辑、“工具”和实现方法。在您的示例中,Objective-C 中没有 block 。

关于ios - 相当于 override init(frame :CGRect) in Swift?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45943437/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com