How to subclass UITableViewController in Swift

后端 未结 9 1823
栀梦
栀梦 2020-12-23 11:42

I want to subclass UITableViewController and be able to instantiate it by calling a default initializer with no arguments.

class TestViewController: UITableV         


        
9条回答
  •  春和景丽
    2020-12-23 12:03

    I did it like this

    class TestViewController: UITableViewController {
    
        var dsc_var: UITableViewController?
    
        override convenience init() {
            self.init(style: .Plain)
    
            self.title = "Test"
            self.clearsSelectionOnViewWillAppear = true
        }
    }
    

    Creating and displaying a instance of TestViewController in a UISplitViewController did work for me with this code. Maybe this is bad practice, please tell me if it is (just started with swift).

    For me there's still a problem when there are non optional variables and the solution of Nick Snyder is the only one working in this situation
    There's just 1 problem: The variables are initialized 2 times.

    Example:

    var dsc_statistcs_ctl: StatisticsController?
    
    var dsrc_champions: NSMutableArray
    
    let dsc_search_controller: UISearchController
    let dsrc_search_results: NSMutableArray
    
    
    override init() {
        dsrc_champions = dsrg_champions!
    
        dsc_search_controller = UISearchController(searchResultsController: nil)
        dsrc_search_results = NSMutableArray.array()
    
        super.init(style: .Plain) // -> calls init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) of this class
    }
    
    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
        // following variables were already initialized when init() was called and now initialized again
        dsrc_champions = dsrg_champions!
    
        dsc_search_controller = UISearchController(searchResultsController: nil)
        dsrc_search_results = NSMutableArray.array()
    
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
    }
    

提交回复
热议问题