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.
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?
The UIView class is a key subclassing point for visual content that also requires user interactions. Although there are many good reasons to subclass UIView , it is recommended that you do so only when the basic UIView class or the standard system views do not provide the capabilities that you need.
Open Xcode ▸ File ▸ New ▸ File ▸ Cocoa Touch class ▸ Add your class name ▸ Select UIView or subclass of UIView under Subclass of ▸ Select language ▸ Next ▸ Select target ▸ Create the source file under your project directory. Programatically create subviews, layout and design your custom view as per requirement.
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()
(Edit: I've edited my answer so that the relation between the initializers is more clear)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With