Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift subclass UIView

Tags:

ios

swift

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?

like image 714
Haagenti Avatar asked Nov 21 '14 08:11

Haagenti


People also ask

What is subclass of UIView?

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.

How do I create a custom view in Swift?

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.


1 Answers

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)

like image 163
Raymond Avatar answered Sep 26 '22 08:09

Raymond