我想動態創建UIViewController而不創建類或使用Mainstoryboard。我希望它以編程方式發生。是否有可能? 我想根據動態數據創建UIViewControllers。在Swift中動態創建uiviewcontroller
4
A
回答
13
是的,您可以通過編程方式動態創建視圖。我知道你說過你不想上課,但你真的必須這樣做。但關鍵是,你不必讓這個類硬編碼UI,而是動態構建它。
因此,您可以繼承UIViewController
,但將它需要的數據傳遞給動態構建視圖,然後實現loadView
方法。不需要NIB或故事板場景。只需創建view
並根據您的動態數據構建子視圖。這在傳統View Controller Programming Guide中進行了描述。 (請注意,該文檔的部分內容不再適用,特別是「卸載」視圖討論的部分內容,但它確實描述並說明了loadView
過程,該過程仍可正常工作。)
構建視圖的過程視圖控制器如下:
正如你可以看到,路徑(自定義loadView
方法)中的一個繞過故事板/ NIB工作流程。請注意,如果您執行此過程,則需要負責實例化UIView
對象並設置視圖控制器的view
屬性。另外,在您的實施中,請而不是請致電super.loadView()
。
例如,如果我想只是一堆UILabel
對象添加到視圖中,斯威夫特3,你可以這樣做:
class DynamicViewController: UIViewController {
var strings: [String]!
override func loadView() {
// super.loadView() // DO NOT CALL SUPER
view = UIView()
view.backgroundColor = .lightGray
let stackView = UIStackView()
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.axis = .vertical
view.addSubview(stackView)
NSLayoutConstraint.activate([
stackView.centerXAnchor.constraint(equalTo: view.centerXAnchor),
stackView.centerYAnchor.constraint(equalTo: view.centerYAnchor)
])
for string in strings {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.text = string
stackView.addArrangedSubview(label)
}
}
}
而且你可以提出它像這樣:
@IBAction func didTapButton(_ sender: AnyObject) {
let controller = ViewController()
controller.strings = ["Hello world", "Foobar", "Baz"]
show(controller, sender: sender)
}
(爲SWIFT 2再現,見previous revision of this answer。)
說了這些之後,我不確定爲什麼你關心不使用NIB或故事板。只需使用一個空白的。然後,您可以再次以編程方式將您的控件動態添加到場景中,但可以在viewDidLoad
中執行。它達到了與上述完全相同的效果,但避免使用相當陳舊的技術,並且必須自己實例化和加載view
屬性。
相關問題
- 1. UIViewController中的Swift動態tableview
- 2. 在Swift 3中創建動態對象
- 3. Swift:動態對象創建
- 4. 在Swift 3中動畫UIViewController
- 5. 如何在一個UIViewController中動態創建多個UITableViews
- 6. 在主UiViewController中動態聲明子UiViewController
- 7. Swift - Animate動態創建的UIImageView
- 8. 如何在iPhone上動態創建UIVIewController標籤?
- 9. 在php中動態創建動態類
- 10. 如何在Swift中創建動態大小的UITableViewCell?
- 11. 如何在swift中創建動態視圖?
- 12. 如何在swift中創建動態堆棧視圖?
- 13. 在SWIFT中創建帶動態值的可變字典
- 14. 在Swift中動態結構創建 - 基於用戶輸入
- 15. 在Swift中動態地使用for循環創建UIButton
- 16. 使用動態名稱在swift中創建變量
- 17. 如何在swift中創建動態的UItextfields?
- 18. 獲取CheckBox在動態創建的GridView中動態創建
- 19. Swift 3:從動態uitableviewcell中的按鈕到uiviewcontroller的popover連接
- 20. UIViewController中的動態UICollectionView
- 21. 如何從NSString名稱動態創建任何UIViewController iOS7.1
- 22. Mvvmcross Touch如何在UIViewController中動態創建自定義控件列表
- 23. 創建一個UIViewController
- 24. 在swift中創建數組
- 25. 在Swift 3中創建UIToolbar
- 26. 在android中動態創建活動
- 27. 動態創建的swift 3/xcode標籤中的行間距
- 28. SWIFT uiviewcontroller init
- 29. 動態創建
- 30. 動態創建
'let viewController = UIViewController()'=)請更好地解釋並向我們展示您在代碼中的嘗試,以獲得更深的答案 –
好的。我會試試這個 –