2015-05-23 61 views
0

我有一個關於繼承UIViewControllers的基本問題,但似乎無法在此處找到答案。我的應用程序有一個UINavigationViewController,我打算有幾個視圖(按順序)。我的第一個ViewController是一個自定義ViewControllerUITableViewDatePicker,並且UIPickerController視圖等創建UIViewController的子類

我想用同樣的ViewController(我猜的一個子類?)所有後續意見。我想使用我在故事板中創建的相同佈局。目前我的代碼是這樣編寫的,在viewDidLoad中,我從plist中讀取一個數組,並填充表和內容的其餘部分。你可以想象,我試圖避免複製粘貼,重複代碼和簡單的方法來同時更改所有視圖。

我知道這應該是相當微不足道的,但我無法弄清楚我需要做什麼改變。另外,我應該用xib創建一個ViewController嗎?有沒有辦法將我的CustomViewController拖拽到Xcode右側的列表中?

回答

1

我認爲你應該創建一個'基'視圖控制器,它將收集所有重複的方法和屬性。它將繼承自UIViewControll,但所有其他控制器將從基地繼承。

您可以複製粘貼在故事板中的連接並與基類中的插座連接,但如果您需要更改某些內容,則會遇到問題。因此,我建議您以編程方式創建它(我認爲xibs已經過去),或者將其替換爲另一個小視圖控制器,然後使用視圖控制器容器來加載它。 enter image description here

如果你有一些事情,重複,但不是每個控制器,你可以創建基類自己的選項是這樣的:

typedef NS_OPTIONS(NSUInteger, BaseOptions) { 
    BaseOptionsNone   = 0, 
    BaseOptionsTableView  = 1 << 0, 
    BaseOptionsDatePicker = 1 << 1, 
    BaseOptionsSomethingElse = 1 << 2 
}; 

@interface BaseViewController : UIViewController 

@property (nonatomic) BaseOptions options; 

@end 

@implementation BaseViewController 

- (void)setOptions:(BaseOptions)options { 
    _options = options; 

    if (self.options & BaseOptionsTableView) { 
     // add table view 
    } 
    if (self.options & BaseOptionsSomethingElse) { 
     // another staff 
    } 
} 

@end 

,然後設置選項到子類:

@interface CustomViewController : BaseViewController 

@end 

@implementation CustomViewController 

- (void)viewDidLoad { 
    [super viewDidLoad]; 

    self.options = BaseOptionsTableView | BaseOptionsSomethingElse; 
} 

@end 

有一個有趣的:)

0

在我看來,你可以創建一個的viewController作爲根的viewController中,你可以imple共同觀點,行動等等。然後,創建其他viewController子類你的rootViewController。

在你的rootViewController中,你可以編寫一些通用代碼,帶或不帶xib。這一切都依賴於你。下面是一個簡單的例子:

//Your RootViewController. 
class rootViewController: UIViewController { 

    override func viewDidLoad() { 
     super.viewDidLoad() 

     let button:UIButton = UIButton(frame: CGRectMake(10, 10, 200, 90)) 
     button.backgroundColor = UIColor.redColor() 
     button.addTarget(self, action: "testButton:", forControlEvents: UIControlEvents.TouchUpInside) 
     view.addSubview(button) 
    } 

    func testButton(button:UIButton) { 
     // Some Common Code. or just keep blank. 
     println("parents") 
    } 

} 


// Your ChildrenViewController. 
class childrenViewController: rootViewController { 
    override func testButton(button:UIButton) { 
     super.testButton(button) 
     // Some code only for this children view controller. 
     println("children") 
    } 
} 

因爲childrenViewController是rootViewController的子類,所有rootViewController的函數都會對它有效。所以childrenViewController會自動在幀(10,10,200,90)中顯示一個redButton。如果你按下按鈕,這將打印「父母」和「孩子」。

希望它可以幫助你。

相關問題