gpt4 book ai didi

ios - Swift:继承 UITextView 或 UICollectionView 并正确初始化

转载 作者:IT王子 更新时间:2023-10-29 05:42:33 29 4
gpt4 key购买 nike

子类化 UITextView(和 UICollectionView)的问题在于指定的构造函数是“initWithFrame”。但在现实生活中,当它从 Storyboard加载时,将调用 initWithCoder。

class BorderedTextView: UITextView {
//will be called
init(coder: NSCoder?){
//constant values here is not an option
super.init(frame: CGRectMake(0,0,100,100), textContainer: nil)
}
//will not be called
init(frame: CGRect, textContainer: NSTextContainer!) {
super.init(frame: frame, textContainer: textContainer)
}
}

因此,我无法在 init 上调用任何 UI 自定义代码,也无法为 Swift 变量提供除默认值之外的任何初始化值。

我想这个问题可以通过从“编码器”中提取帧大小来暂时解决,但我没有找到它的关键。

有什么比硬编码帧值更好的想法吗?

最佳答案

(来 self 上面的评论:)这看起来像一个 Swift 错误。 initWithCoder: 调用时 View (或 View Controller )从 Storyboard或 Nib 文件实例化,并覆盖该方法适用于 Objective-C:

- (instancetype)initWithCoder:(NSCoder *)aDecoder
{
self = [super initWithCoder:aDecoder];
if (self) {
// Initialization code
}
return self;
}

但是等效的 Swift 代码

class BorderedTextView: UITextView {
init(coder: NSCoder!) {
super.init(coder: coder)
}
}

失败并显示错误消息“必须调用父类(super class)‘UITextView’的指定初始化程序”。

UIView 的所有子类都会出现此问题他们自己指定的初始化器(例如 UITextViewUICollectionView)。另一方面,UILabel 的子类不会出现此问题,它没有指定的初始值设定项。Swift 语言对于调用父类(super class)的指定初始化器非常严格,但应该有一种方法可以覆盖所有自定义 UIView 子类的 initWithCoder:,所以我认为这是一个 Swift 错误。

作为解决方法,您可以在

中进行自定义初始化
override func awakeFromNib() {
super.awakeFromNib()
// ...
}

Swift 1.2 更新:这显然已得到修复。参数改变了,它不再是一个隐式解包的可选。所以这按预期编译和工作(使用 Xcode 6.4 测试):

class BorderedTextView: UITextView {
required init(coder: NSCoder) {
super.init(coder: coder)

// ...
}
}

Swift 2 (Xcode 7) 的更新: init(coder:) 是一个失败的现在初始化:

class BorderedTextView: UITextView {
required init?(coder: NSCoder) {
super.init(coder: coder)

// ...
}
}

关于ios - Swift:继承 UITextView 或 UICollectionView 并正确初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24477082/

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