How to subclass UITableViewController in Swift

后端 未结 9 1840
栀梦
栀梦 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:11

    Props to matt for a great explanation. I've made use of both matt's and @Nick Snyder's solutions, however I ran into a case in which neither would quite work, because I needed to (1) initialize let fields, (2) use init(style: .Grouped) (without getting a runtime error), and (3) use the built-in refreshControl (from UITableViewController). My workaround was to introduce an intermediate class MyTableViewController in ObjC, then use that class as the base of my table view controllers.

    MyTableViewController.h

    #import 
    // extend but only override 1 designated initializer
    @interface MyTableViewController : UITableViewController
    - (instancetype)initWithStyle:(UITableViewStyle)style NS_DESIGNATED_INITIALIZER;
    @end
    

    MyTableViewController.m:

    #import "MyTableViewController.h"
    // clang will warn about missing designated initializers from
    // UITableViewController without the next line.  In this case
    // we are intentionally doing this so we disregard the warning.
    #pragma clang diagnostic ignored "-Wobjc-designated-initializers"
    @implementation MyTableViewController
    - (instancetype)initWithStyle:(UITableViewStyle)style {
        return [super initWithStyle:style];
    }
    @end
    

    Add the following to Project's Bridging-Header.h

    #import "MyTableViewController.h"
    

    Then use in swift. Example: "PuppyViewController.swift":

    class PuppyViewController : MyTableViewController {
        let _puppyTypes : [String]
        init(puppyTypes : [String]) {
            _puppyTypes = puppyTypes // (1) init let field (once!)
            super.init(style: .Grouped) // (2) call super with style and w/o error
            self.refreshControl = MyRefreshControl() // (3) setup refresh control
        }
        // ... rest of implementation ...
    }
    

提交回复
热议问题