![](/img/trans.png)
[英]iOS Swift, with one common method in protocol and two implementations in two ViewControllers, how to decide which ViewControllers method is invoked?
[英]How can I add a common view to multiple ViewControllers in iOS Swift?
我是iOS開發的新手。
我想在其中包含一個自定義視圖和一些標簽。 然后在我的應用程序的某些viewControllers中,單擊一個按鈕,我想在該viewController的底部添加/顯示該View。
就我要在其中要顯示視圖的所有viewController中的情節提要中手動添加視圖而言。 但這不是有效的。 如何在單擊按鈕時以編程方式在viewControllers中添加此視圖?
使一個BaseViewController類繼承自UIViewController
現在在BaseViewController中創建名為designFooter的方法
func designFooter() {
var viewFooter: UIView = UIView(frame: CGRectMake(0, self.view.bounds.size.height - 50, self.view.bounds.size.width, 50))
viewFooter.backgroundColor = UIColor.redColor()
self.view!.addSubview(viewFooter)
}
對於Swift 4、5.1:
func designFooter() {
let viewFooter: UIView = UIView(frame: CGRect(x:0, y:self.view.bounds.size.height - 50, width:self.view.bounds.size.width, height:50))
viewFooter.backgroundColor = UIColor.red
self.view.addSubview(viewFooter)
}
現在,將此BaseViewController繼承到要在其中添加頁腳的ViewController,然后在按鈕上單擊,只需調用self.designFooter()
如果要添加的子視圖具有一些動態內容或具有很多自己的邏輯,則可能要使用視圖控制器包含,特別是不僅要添加子視圖,還要添加與該子視圖關聯的控制器。 因此,您可以在情節提要中為該子視圖提供一個場景,該場景將顯示在底部,並將其與自己的視圖控制器關聯。 然后,當您想要添加它時,您將執行以下操作:
let child = storyboard!.instantiateViewController(withIdentifier: "storyboardid")
addChild(child)
// set the `frame` or `constraints` such that it is in the correct place, perhaps animating it into place
view.addSubview(child.view)
child.didMove(toParent: self)
當您要刪除它時:
child.willMove(toParent: nil)
child.view.removeFromSuperview()
removeChild(child)
就個人而言,如果它真的可以在我的應用程序中的任何場景中出現或消失,那么我實際上會將整個應用程序嵌入到容器視圖控制器中。 然后,在此主容器視圖控制器上,此子項的彈出和彈出僅需執行一次。
例如,考慮以下情節提要:
那是一個嵌入式的“容器視圖”(相當於故事板的視圖控制器包含,如上所述)。 然后,我可以在外面制作一個標簽動畫(通過更改帶有標簽的某些視圖的高度約束后,對layoutIfNeeded
進行動畫處理)。 然后,無論當前可見哪個視圖控制器的視圖,此底視圖都可以進行動畫處理:
只需創建一個UIView並調用addSubview即可:
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0,0,100,100)];//change this frame for your purposes
UILabel *l = [[UILabel alloc] initWithFrame:CGRectMake(10,10,50,10)];
[l setText: @"My label"];
[view addSubview: l];
[self.view addSubview: view];
至於將其添加到多個視圖控制器中……我想如果您有許多具有相同UIView的不同視圖控制器,則可以創建UIViewController的子類,稱為CustomViewController。 在該類中,將上面的代碼添加到viewDidLoad中。 然后,在所有具有特定視圖的視圖控制器中子類化CustomViewController,它們將自動為您添加它。
編輯:如果要在界面構建器中設計視圖,請創建UIView的自定義子類。 我們將此稱為CustomView。 在筆尖中進行設計,然后添加所需的任何代碼。 然后,無論何時要創建該視圖,只需調用CustomView *cv = [[CustomView alloc] initWithFrame:...]
,然后執行[self.view addSubview:cv];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.