gpt4 book ai didi

ios - 在 Xcode 中拥有多个 Storyboard

转载 作者:搜寻专家 更新时间:2023-11-01 07:09:10 26 4
gpt4 key购买 nike

问题:在带有 TableView 的 xib 中创建了一个 View Controller 。但是,表格 View 的行为非常奇怪,看起来不像我们在 Storyboard 中使用的表格 View 。

enter image description here

我的计划是用我在另一个 xib 文件中创建的自定义表格 View 单元格填充此表格 View 。但是,遗憾的是,它没有像我预期的那样工作,因为一切都已关闭并且这些单元格已实例化,我知道我的自定义单元格可以工作,因为它在我在 Storyboard 中创建的其他 View Controller 中工作:

]]]]]]

我想要一种方法来设计我的 View Controller ,这样我就可以在需要时实例化它们,我这样做的原因是我不想有一个非常丰富的 Storyboard。现在我知道我不能像在 Storyboard 中那样在 xib 文件中使用 TableView 。有解决办法吗?我需要另一个 Storyboard来实现吗?

最佳答案

任务 1. 从 Xib 加载 UIViewcontroller

我们可以加载一个 UIViewcontroller 表单 Xib 而不是 Storyboard。我们可以使用以下程序:

<强>1。创建一个 UIViewcontroller。

 XCode File -> New -> File -> Cocoa Touch Class -> Fill Class with your class name , subclass of with UIViewController , check Also create Xib file, language Swift -> Next - Create.

Example: ViewControllerFromXib

<强>2。覆盖 init()。

override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) 
{
super.init(nibName: "ViewControllerFromXib", bundle: Bundle.main)
}

required init?(coder aDecoder: NSCoder)
{
super.init(coder:aDecoder)
}

<强>3。打开新创建的Controller

let controller = ViewControllerFromXib.init()
self.present(controller, animated: true, completion: nil)

通过以上方式,我们可以从 XIB 加载一个 UIViewcontroller。

任务 2. 创建一个 TableView 并使用自定义 xib 填充它的单元格

<强>1。创建自定义 UItableViewCell

XCode File -> New -> File -> Cocoa Touch Class -> Fill Class with your cell name , subclass of with TableViewCell , 勾选 Also create Xib file, language Swift -> Next - Create.

示例:CustomTableViewCell

1.为您的 TableView 注册 UItableViewCell。

override func viewDidLoad() {
super.viewDidLoad()
self.title = "Item"
self.tableView.register(UINib(nibName: "CustomTableViewCell", bundle:Bundle.main), forCellReuseIdentifier: "CustomTableViewCell");
}

<强>2。将 UITableViewDataSource 实现到您的 View Controller 中

extension ViewControllerFromXib:UITableViewDataSource {

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 3;
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

let cell = tableView.dequeueReusableCell(withIdentifier: "CustomTableViewCell", for: indexPath) as! CustomTableViewCell
return cell

}

}

<强>2。在您的 View Controller 中实现 UITableViewDelegate。

extension ViewControllerFromXib:UITableViewDelegate {

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat{

return UITableViewAutomaticDimension;

}

}

关于ios - 在 Xcode 中拥有多个 Storyboard,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45872995/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com