我是 Swift 编程新手。我有一个带有单个自定义单元格的表格 View 。在页面顶部我有一个段控件。在我的自定义单元格中,我有两个标签和文本字段。当页面加载时,段控制中的第一个段将处于选定状态,表行数应为 5。
如果选择段中的第二个选项,我应该再加载一行,即第 6 行,并隐藏第二行中的一个文本字段。能够加载 5 行的表格 View 。当用户从段中选择时,我无法重新加载包含 6 行的表。这是我的代码,
class FirstViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
let numberOfRowsAtSection: [Int] = [5, 6]
var selectedOption: Bool = false
override func viewDidLoad() {
super.viewDidLoad()
reportTable.delegate = self
reportTable.dataSource = self
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
var rows: Int = 0
if tableView == self.reportTable && selectFromOptions.selectedSegmentIndex == 0 && selectedOption == true {
selectedOption = false;
if section == 0 {
rows = 5
}
} else if selectFromOptions.selectedSegmentIndex == 1 && selectedOption == true {
if section == 1 {
rows = 6
}
}
return rows
}
@IBAction func optionChanges(sender: UISegmentedControl) {
switch selectFromOptions.selectedSegmentIndex {
case 0:
selectedOption = true
reportTable.reloadData()
case 1:
selectedOption = true
reportTable.reloadData()
default:
break;
}
}
我怎样才能实现上述目标?提前致谢。
最佳答案
您的代码中有一个错误,您检查了 ifsection == 1
部分。只有一个部分,其索引始终为 0。您应该能够通过在 selectedOption
中设置断点并单步执行以查看传入的值以及所走的代码路径来发现这一点下来。
我认为这应该有效:
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
var rows: Int = 0
if tableView == self.reportTable && selectFromOptions.selectedSegmentIndex == 0 && selectedOption == true {
selectedOption = false;
if section == 0 {
rows = 5
}
} else if selectFromOptions.selectedSegmentIndex == 1 && selectedOption == true {
if section == 0 {
rows = 6
}
}
return rows
}
我没有您代码的完整上下文,但上面似乎可能存在一些不必要的条件。这不会产生预期的结果吗?
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch selectFromOptions.selectedSegmentIndex {
case 0:
return 5
case 1:
return 6
default:
return 0
}
}
关于ios - 更新段中的行数以进行段控制选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38413289/