【问题标题】:Populate TableView at button push in xCode在 xCode 中按下按钮时填充 TableView
【发布时间】:2022-01-20 15:51:37
【问题描述】:

我创建了一个程序,它有几个显示随机数集的屏幕;填充标签时一切正常。

不过,对于其中一个屏幕,我需要显示两个独立的结果。我用 Label 试过这个,但看起来不太好,所以我考虑使用 TableView,现在将结果数据实际推送到表的行是一个相当大的挑战。

代码如下所示:

    class EController: UIViewController {

    @IBOutlet var tableView: UITableView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        tableView.dataSource = self
    
    }
    
    func allTogether(_ SetB:Set<Int>, _ Scope:ClosedRange<Int>) -> (Set<Int>){

        func iterateNremove2() -> (Set<Int>, Set<Int>){
        
            var nums = SetB
            let scp = Scope
        
            var reslts = Set<Int>()
        
            for _ in scp{
                let randNum = nums.randomElement()!
                reslts.insert(randNum)
                nums.remove(randNum)
            }
        
            return (nums, reslts)
        }

        let go = iterateNremove2()
        let res = go.1

        return (res)
    }
    
    @IBAction func Erand(_ sender: Any) {
        
        let it = allTogether(Set(1...45), 1...10)
        let that = allTogether(Set(1...9), 1...3)

        let eStrngM = it.map(String.init).joined(separator: ", ")
        let eStrngS = that.map(String.init).joined(separator: ", ")

        let finRslts = [eStrngM, eStrngS]
        
    }
    
    
}

extension EController: UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 2
    }
        
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) ->UITableViewCell {
        let cell  = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        
        cell.textLabel?.text = finRslts[indexPath.row]
        
        return cell
    }
    
}

抱歉这么大,但问题可能分散在代码中,或者整个解决方案可能有问题(这是我看完教程后想到的)。

当调用“cell.textLabel?.text”时,我得到的唯一错误是“在范围内找不到 finRslts”。

我尝试在不同类之间移动随机化函数和按钮的@IBAction,但错误始终相同。我要么错过了一些小东西,不知道如何搜索它,要么整个解决方案有问题。请帮忙。

【问题讨论】:

    标签: xcode uitableview ibaction


    【解决方案1】:

    你必须创建finRslts——顺便说一句,Swift 没有像 Windows 95 中那样的 8+3 变量名限制——在类的顶层,就在表视图出口之后。

    var finalResults = [String]()
    

    Erand 中替换

    let finRslts = [eStrngM, eStrngS]
    

    finalResults = [eStrngM, eStrngS]
    tableView.reloadData()
    

    最好在numberOfRowsInSection中返回数组中的项目数

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return finalResults.count
    }
    

    【讨论】:

    • 非常感谢@vadian!现在它工作得很好:)
    猜你喜欢
    • 1970-01-01
    • 2018-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-17
    • 2016-09-14
    • 1970-01-01
    相关资源
    最近更新 更多