ios - 更新段中的行数以进行段控制选择

标签 ios swift uitableview

我是 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/

相关文章:

ios - 目标文件不包含 DWARF 调试信息

ios - 解析iOS初学者: getting an exception on PFUser signup

swift - 在 Swift 中,冒号后面有类型声明有什么作用?

swift - 在 Swift 中将一行作为选择指示器添加到 UITabbarItem

ios - 如何制作一个简单的TableView?

iphone - 应用程序在启动时崩溃,仅更新而不是全新安装

iphone - iOS - 带方向的反转高度/宽度

swift - 多列文本窗口 Cocoa Swift NSTextView

objective-c - 在 0 : 8/attempt to write a readonly database 之后意外无法执行 BEGIN IMMEDIATE

swift - 在 tableview 中显示两个可重用的单元格 - Swift 3