在我的应用程序中,我有相同的 UI 组件,应该在不同的 ViewControllers 中呈现。这个组件看起来像按钮列表,点击每个按钮应该用一些参数推送 VievController - 我决定使用 UITableView 。
假设我有 ViewControllers: VC1,VC2,VC3 应在其中显示此 UITableView。应在每个 ViewController 中显示的单元格数量存储在名为button 的数组中。
struct Button {
var title : String
var param : Int
}
class VC1 : UIViewController {
var buttons = [Button]()
}
现在我正在每个 ViewController 中创建这个 tableView,比如
class VC1 : UIViewController, UITableViewDelegate, UITableViewDataSource {
var buttons = [Button]()
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return buttons.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
....
return btnCell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue....
}
}
您可以将所有 UI 元素放在 xib 中,并在该 xib 类中处理 tableView 委托。如果你想在 xib 和 VC1 之间进行通信,你可以编写一个协议。或者第二种方法非常相似,您可以创建一个UIelemntsVC
包含所有 UI 元素(tableView、按钮等)的 viewController(让其命名)并将其加载到您的 VC1、VC2、VC3 等中。
在UIelementsVC
课堂上你可以像这样控制它的大小
self.view.frame = CGRect(x: 0, y: UIScreen.main.bounds.height, width: self.view.frame.width, height: self.view.frame.height*2)
如果你想使用自动布局,那么你应该在你的 VC1 中放置一个 UIViewUIelementsVC
并向它添加子视图。
您可以像这样加载自定义 ViewController:
let customVC = UIelementsVC()
customVC.customDelegate = self // Only if you have a custom protocol
customVC.numberOfButtons = 5 // You can edit vars in customVC like this
self.addChildViewController(customVC)
self.view.addSubview(customVC)
customVC(toParentViewController: self)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句