Swift子类UIView [英] Swift subclass UIView
问题描述
我想继承UIView
的类,并显示类似视图的登录名.我已经在Objective-C中创建了它,但是现在我想将其移植到Swift.我不使用情节提要,所以我用代码创建了所有UI.
I want to subclass UIView
and show a login like view. I've created this in Objective-C, but now I want to port it to Swift. I do not use storyboards, so I create all my UI in code.
但是第一个问题是我必须实现initWithCoder
.我给了它一个默认的实现,因为它不会被调用.现在,当我运行程序时,它崩溃了,因为我还必须实现initWithFrame
.现在我明白了:
But the first problem is that I must implement initWithCoder
. I gave it a default implementation since It won't be called. Now when I run the program it crashes, because I've to implement initWithFrame
as well. Now I got this:
override init() {
super.init()
println("Default init")
}
override init(frame: CGRect) {
super.init(frame: frame)
println("Frame init")
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
println("Coder init")
}
我的问题是我应该在哪里创建文本字段等?如果我从不实现框架和编码器,该如何隐藏"?这个吗?
My question is where should I create my textfield etc... and if I never implement frame and coder how can I "hide" this?
推荐答案
我通常会这样做,但有点冗长.
I usually do something like this, its a bit verbose.
class MyView: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
addBehavior()
}
convenience init() {
self.init(frame: CGRect.zero)
}
required init(coder aDecoder: NSCoder) {
fatalError("This class does not support NSCoding")
}
func addBehavior() {
print("Add all the behavior here")
}
}
let u = MyView(frame: CGRect.zero)
let v = MyView()
(我已经编辑了答案,以使初始化程序之间的关系更加清晰)
( I've edited my answer so that the relation between the initializers is more clear)
这篇关于Swift子类UIView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!