How to Subclass Custom Uiviewcontroller in Swift

How do I make a custom initializer for a UIViewController subclass in Swift?

class ViewController: UIViewController {

var imageURL: NSURL?

// this is a convenient way to create this view controller without a imageURL
convenience init() {
self.init(imageURL: nil)
}

init(imageURL: NSURL?) {
self.imageURL = imageURL
super.init(nibName: nil, bundle: nil)
}

// if this view controller is loaded from a storyboard, imageURL will be nil

required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}

How to subclass custom UIViewController in Swift?

When you instantiate a view controller via instantiateViewControllerWithIdentifier, the process is essentially as follows:

  • it finds a scene with that identifier;
  • it determines the base class for that scene; and
  • it returns an instance of that class.

And then, when you first access the view, it will:

  • create the view hierarchy as outlined in that storyboard scene; and
  • hook up the outlets.

(The process is actually more complicated than that, but I'm trying to reduce it to the key elements in this workflow.)

The implication of this workflow is that the outlets and the base class are determined by the unique storyboard identifier you pass to instantiateViewControllerWithIdentifier. So for every subclass of your base class, you need a separate storyboard scene and have hooked up the outlets to that particular subclass.

There is an approach that will accomplish what you've requested, though. Rather than using storyboard scene for the view controller, you can instead have the view controller implement loadView (not to be confused with viewDidLoad) and have it programmatically create the view hierarchy needed by the view controller class. Apple used to have a nice introduction to this process in their View Controller Programming Guide for iOS, but have since retired that discussion, but it can still be found in their legacy documentation.

Having said that, I personally would not be compelled to go back to the old world of programmatically created views unless there was a very compelling case for that. I might be more inclined to abandon the view controller subclass approach, and adopt something like a single class (which means I'm back in the world of storyboards) and then pass it some identifier that dictates the behavior I want from that particular instance of that scene. If you want to keep some OO elegance about this, you might instantiate custom classes for the data source and delegate based upon some property that you set in this view controller class.

I'd be more inclined to go down this road if you needed truly dynamic view controller behavior, rather than programmatically created view hierarchies. Or, even simpler, go ahead and adopt your original view controller subclassing approach and just accept that you'll need separate scenes in the storyboard for each subclass.

How to subclass a UIViewController and add properties in swift?

At some point the view controller must be initialized by calling init(nibName:bundle:) or init(coder:)

Try this:

class MyViewController: UIViewController {

var prop: Int

init(prop: Int, nibName nibNameOrNil: String? = nil, bundle nibBundleOrNil: Bundle? = nil) {
self.prop = prop
super.init(nibName:nibNameOrNil, bundle: nibBundleOrNil)
}

required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}

}

How to sub class custom view controller in swift?

Just do what the error message says: You need to implement init?(coder.

The basic implementation is to call super and do the same things as in init(nibName

required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
tableView = tableViewObj
}

accessing UIView subclass in view controller

Posting my own answer.

  1. Create the XIB file.
  2. Create the UIView subclass Swift file.
  3. Under the XIB file owner's Identify Inspector custom class field, type in the UIView subclass name (your custom view).
  4. Under the XIB file owner's Connections Inspector, make sure all IBOutlets in the Swift file are connected.
  5. Add a view to the view controller and under its Identify Inspector custom class type, specify the custom class name.

Important:
* In your XIB swift file, you have to properly load the XIB content view.

...

/// Initializer used by Interface Builder.
required init?(coder: NSCoder) {
super.init(coder: coder)
configure()
}

/// Initializer used programmatically.
override init(frame: CGRect) {
super.init(frame: frame)
configure()
}

...

func configure() {
let contentView = // here use many of the functions available on the internet to
// load a view from a nib.
// Then add this view to the view hierarchy.
addSubview(contentView)
}

How to subclass an UIViewController with UITableViewDelegate in many subclasses

What you're trying to do doesn't really work that way. The @IBOutlets are all connected through the Storyboard - but they don't "flow through" in the pattern you're hoping to use.

You can do it - in a way. Take a look a the discussion and answers in this SO post: How to subclass custom UIViewController in Swift?

Alternatively, if you're goal is to use a "common" table view controller - but allow customization - you can create separate UITableViewDelegate and UITableViewDataSource files, plus separate visually designed cells, and then assign them via code as desired.

Can I subclass a custom view controller

In the world of object-oriented programming, objects are categorized into hierarchical groups. Rather than using distinct terms for the different hierarchical levels such as genus or species, objects are simply organized into classes. In the same way that humans inherit certain characteristics as members of family, a class can be set to inherit functionality from a parent class.

When one class inherits from another, the child inherits all the behavior and properties defined by the parent. It also has the opportunity either to define its own additional behavior and properties, or override the behavior of the parent.

Long story short, yes, you can and you should create subclass(es) in such cases. This is how you do in Objective-c in .h file (in your new class)

  @interface MySecondController : CalendarTableViewController {
}

In Swift

  class MySecondController: CalendarTableViewController {
// subclass definition goes here
}

I hope it helps

In swift how does one downcast a UIViewController to subclass of a subclass while retaining data?

The reason (well, part of the reason) you are not getting the changed value of "hello" is because:

override func viewDidLoad() {
super.viewDidLoad()
let cl = (self.storyboard?.instantiateViewController(withIdentifier: "contact_list_view"))
contact_list_controller = cl as? ContactListViewController
contact_list_controller?.string ?? "default")
}

instantiateViewController creates a new instance of the specified view controller each time you call it. So, no matter what else you are doing to it after that line, you will never get the value you were trying to set in switchToContractViewForAdd()

Instead, you need to look into "passing data between view controllers" (you'll find uncountable examples and explanations out there by simple searching).

Swift: Initialization of UIViewController subclass with custom parameters

You can write class func for your view controller:

class MyViewController {
// ...
class func instantiate(dataSource: MyDataSource, cellAndHeaderManager: MyCellAndHeaderManager) -> MyViewController {
let vc = UIStoryboard(name: "Storyboard", bundle: nil).instantiateViewControllerWithIdentifier("MyViewController") as! MyViewController
vc.dataSource = dataSource
vc.cellAndHeaderManager = cellAndHeaderManager
return vc
}
}

So you can instantiate it with:

let vc = MyViewController.instantiate(dataSource: dataSource, cellAndHeaderManager: cellAndHeaderManager)

You can not instantiate view controller from Storyboard with initializer because there is no suitable initializer in UIViewController.



Related Topics



Leave a reply



Submit