如何在swift 4中动态加载tableview
我用Worm Tab Strip cocoapod获得了类似android的选项卡,选项卡的名称来自服务器响应,我需要n个基于选项卡名称数量的视图控制器 出于测试目的,我有硬编码的选项卡名称,对于每个特定的选项卡名称,我有另一个子名称数组。我的问题是如何更改tableview内容,以便根据选项卡名称获得确切数量的子名称如何在swift 4中动态加载tableview,swift,tableview,Swift,Tableview,我用Worm Tab Strip cocoapod获得了类似android的选项卡,选项卡的名称来自服务器响应,我需要n个基于选项卡名称数量的视图控制器 出于测试目的,我有硬编码的选项卡名称,对于每个特定的选项卡名称,我有另一个子名称数组。我的问题是如何更改tableview内容,以便根据选项卡名称获得确切数量的子名称 var tabNames = ["Brands", "Sports","Movies", "Mobile","Games"] var brandsNames = ["Addida
var tabNames = ["Brands", "Sports","Movies", "Mobile","Games"]
var brandsNames = ["Addidas", "Nike","Puma"]
var sportsName = ["Cricket","Fifa","Hockey","Baseball"]
var moviesName = ["Mission Impossible","Matrix","Avatar","Titanic"]
var mobileNames = ["Nokia","Redmi","Samsung"]
var gameNames = ["FIFA 19","PES 19","WWE 2K19","Max Payne"]
我应该试穿什么
func tableView(_ tableView: UITableView, numberOfRowsInSection
section: Int) -> Int {
// return fruits.count
}
及
我需要获得品牌标签,我需要品牌名称作为tableview
内容
tableview内容必须根据选项卡名称进行更改。例如,创建自定义结构作为数据模型
struct Category {
let name : String
let items : [String]
}
声明数据源数组和索引
var categories = [Category]()
var index = 0
在viewdiload
中填充数据源数组,并设置UISegmentedControl的当前索引的index
categories = [Category(name:"Brands", items: ["Addidas", "Nike","Puma"]),
Category(name:"Sports", items: ["Cricket","Fifa","Hockey","Baseball"]),
Category(name:"Movies", items: ["Mission Impossible","Matrix","Avatar","Titanic"]),
Category(name:"Mobile", items: ["Nokia","Redmi","Samsung"]),
Category(name:"Games", items: ["FIFA 19","PES 19","WWE 2K19","Max Payne"])]
index = // current index of the segmented control
在分段控件的iAction
中,设置索引并重新加载表视图
@IBAction func categorySelection(_ sender: UISegmentedControl) {
index = sender.selectedSegmentIndex
tableView.reloadData()
}
数据源方法是
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return categories[index].items.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! Cell1
cell.textLabel?.text = categories[index].items[indexPath.row]
return cell
}
我使用它作为参考,这样我可以在viewcontroller中将特定选项卡的ID传递给tableview,并加载该tableview,这样现在我可以动态添加新选项卡,相应的tableview也会更改先生,实际上我没有使用分段控件,我将从温暖的选项卡CoCoCoapod获取所选选项卡的ID,因此,根据id如何重新加载TableView我不知道这个库,但我猜有一个属性指示索引和一个在用户更改选项卡时调用的操作。先生,有没有什么解决方案,比如只使用一个viewcontroller并根据所选选项卡idSir更改其内容,我使用了下面的方法,得到了结果
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return categories[index].items.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! Cell1
cell.textLabel?.text = categories[index].items[indexPath.row]
return cell
}