ios 从每个 UITableView Cells Swift 中获取数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28431086/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 04:47:12  来源:igfitidea点击:

getting data from each UITableView Cells Swift

iosswift

提问by Chan Woo

I have searched the internet countless times and have not found a solution to my situation. Things that may be a solution are things I didn't understand and they were in Objective-C. So if this is a duplicate, it isn't. I have failed to get a solution from other posts.

我在互联网上搜索了无数次,但没有找到解决我情况的方法。可能是解决方案的事情是我不理解的事情,它们在 Objective-C 中。因此,如果这是重复的,则不是。我未能从其他帖子中获得解决方案。

I am making a GPA Calculator specifically for my school where we get different points depending on our subject levels too.

我正在专门为我的学校制作 GPA 计算器,根据我们的学科水平,我们也会获得不同的分数。

I made a UITableView with a custom cell that will be duplicated specific amount of times each for each subject in the grade.

我制作了一个带有自定义单元格的 UITableView,该单元格将为年级中的每个科目复制特定的次数。

What I want to know is getting the data from each of these custom cells(the score and the level)

我想知道的是从每个自定义单元格中获取数据(分数和级别)

So this is my storyboard:

所以这是我的故事板:

Storyboard

故事板

and this is my app previewed in the simulator:

这是我在模拟器中预览的应用程序:

App Screenshot

应用截图

I'm going to get the score and the level by getting the text of the labels in each subjects and I have no idea how to get data from specific cells.

我将通过获取每个主题中的标签文本来获得分数和级别,但我不知道如何从特定单元格获取数据。

Thank you very much.

非常感谢。

Here's the code i currently have:

这是我目前拥有的代码:

//showStepperValueLabel shows the level and showSliderValueLabel shows the score in the cells.
//customCell is my custom class for my custom cell.
//i have already declared the levels and scores array above in my class

func tableView(tableView: UITableView!, didDeselectRowAtIndexPath indexPath: NSIndexPath!) {
    let cell = tableView.cellForRowAtIndexPath(indexPath) as customCell
    var level: String! = cell.showStepperValueLabel.text
    var score: String! = cell.showSliderValueLabel.text
    levels[indexPath.row] = level
    scores[indexPath.row] = score

}


//yadiyadayada 



//and this is the part where the values get received(it's inside the prepareForSegue function)

    var engScore: String = scores[0]
    var engLevel: String = levels[0]
    var mathScore: String = scores[1]
    var mathLevel: String = levels[1]
    var sciScore: String = scores[2]
    var sciLevel: String = levels[2]
    var geoScore: String = scores[3]
    var geoLevel: String = levels[3]
    var hisScore: String = scores[4]
    var hisLevel: String = levels[4]
    var chiScore: String = scores[5]
    var chiLevel: String = levels[5]
    //

But i'm getting an error where the arrays never received the values. can someone help?

但是我收到一个错误,其中数组从未收到过值。有人可以帮忙吗?

EDIT:

编辑:

i got an error again so i tried giving the strings manually to the arrays while its initialization like

我再次遇到错误,所以我尝试在初始化时将字符串手动提供给数组

var levels: [String] = ["H", "H", "H", "H", "H", "H"]
var scores: [String] = ["12", "23", "34", "45", "56", "67"]

and the program worked perfectly fine. So that concludes that the problem occurs in the part where the array receives the strings which is

并且该程序运行良好。所以得出的结论是问题发生在数组接收字符串的部分

func tableView(tableView: UITableView!, didDeselectRowAtIndexPath indexPath: NSIndexPath!) {
    let cell = tableView.cellForRowAtIndexPath(indexPath) as customCell
    var level: String! = cell.showStepperValueLabel.text
    var score: String! = cell.showSliderValueLabel.text
    levels.insert(level, atIndex: indexPath.row)
    scores.insert(level, atIndex: indexPath.row)

}

are you sure the disselect thing is the correct way? everyone else in the internet taught me to use tags however didn't tell me how to use it...

你确定取消选择是正确的方法吗?互联网上的其他人都教我使用标签,但没有告诉我如何使用它...

EDIT2:

编辑2:

so i tried using tags. this is what i wrote in the tableView: cellForRowAtIndexPath function

所以我尝试使用标签。这是我在 tableView 中写的: cellForRowAtIndexPath 函数

cell.showStepperValueLabel.tag = indexPath.row+10
cell.showSliderValueLabel.tag = indexPath.row

and this is what i wrote in the prepareForSegue

这就是我在 prepareForSegue 中写的

var engScore : UILabel! = self.view.viewWithTag(0) as? UILabel
    var mathScore: UILabel! = self.view.viewWithTag(1) as? UILabel
    var sciScore: UILabel! = self.view.viewWithTag(2) as? UILabel
    var geoScore: UILabel! = self.view.viewWithTag(3) as? UILabel
    var hisScore: UILabel! = self.view.viewWithTag(4) as? UILabel
    var chiScore: UILabel! = self.view.viewWithTag(5) as? UILabel

    var engLevel: UILabel! = self.view.viewWithTag(10) as? UILabel
    var mathLevel: UILabel! = self.view.viewWithTag(11) as? UILabel
    var sciLevel: UILabel! = self.view.viewWithTag(12) as? UILabel
    var geoLevel: UILabel! = self.view.viewWithTag(13) as? UILabel
    var hisLevel: UILabel! = self.view.viewWithTag(14) as? UILabel
    var chiLevel: UILabel! = self.view.viewWithTag(15) as? UILabel

so in the functions of calculating GPA i put

所以在计算 GPA 的函数中,我把

//Get pxcs
    engpxc = engCredits*co.getEnglishPoints(engLevel.text!, engScore: engScore.text!)
    mathpxc = mathCredits*co.getNonLanguagePoints(mathLevel.text!, scoreRecieved: mathScore.text!)
    geopxc = geoCredits*co.getNonLanguagePoints(geoLevel.text!, scoreRecieved: geoScore.text!)
    hispxc = hisCredits*co.getNonLanguagePoints(hisLevel.text!, scoreRecieved: hisScore.text!)
    scipxc = sciCredits*co.getNonLanguagePoints(sciLevel.text!, scoreRecieved: sciScore.text!)
    chipxc = chiCredits*co.getChiPoints(chiLevel.text!, chiScore: chiScore.text!)
    //

and now i'm getting an error that says

现在我收到一个错误,说

fatal error: unexpectedly found nil while unwrapping an Optional value (lldb)

致命错误:在展开可选值 (lldb) 时意外发现 nil

can someone help me with this?

有人可以帮我弄这个吗?

EDIT3 - more info:

EDIT3 - 更多信息:

i added println in the tableView: cellForRowAtIndexPath function in parts where i give the tags and found out that the tags were given successfully and those labels received the tags i assigned in the program however when i checked with println in the prepareForSegue function in where the variables receive their views to see if they received the labels successfully but i got 'nil' there. What in the world is the problem?

我在 tableView: cellForRowAtIndexPath 函数中添加了 println 在我给出标签的部分中,发现标签已成功给出,并且这些标签收到了我在程序中分配的标签,但是当我在 prepareForSegue 函数中检查 println 时,其中的变量收到他们的意见,看看他们是否成功收到了标签,但我在那里得到了“零”。这到底是什么问题?

回答by Miknash

First retrieve your cell where you need it (for instance in didSelectRowAtIndexPath). Cast your UITableViewCell in your custom cell. And then access properties of your cell as you wish.

首先检索您需要的单元格(例如在 didSelectRowAtIndexPath 中)。将您的 UITableViewCell 投射到您的自定义单元格中。然后根据需要访问单元格的属性。

Since you haven't provided any code, I will provide simply examples of the code:

由于您尚未提供任何代码,我将提供简单的代码示例:

func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
    let cell = tableView.cellForRowAtIndexPath(indexPath) as YourCell
    //cell.value, cell.text, cell.randomValue or whatever you need
}

What about submit button, you want to submit the data right? And you don't have indexPath there...

提交按钮怎么样,你想提交数据吗?而且你那里没有 indexPath ......

Well you have several options, one is to go through each cell, check the type and get it. But seems like your each cell is different one. And seems like you have order for these cells. So you know where exactly your result will be. So, in submit you can do the following

那么你有几种选择,一种是通过每个单元格,检查类型并获取它。但似乎你的每个细胞都是不同的。似乎您对这些单元格有订单。所以你知道你的结果会在哪里。因此,在提交时,您可以执行以下操作

@IBAction func submit_pressed(sender: UIButton) {
     var indexs = NSIndexPath.init(index: 10)
     // or which one(s) you need. you extract data from the cell similar to previous function
}

But, why do you have to get entire cell to get one value? How about you create few variables (or even better, array) and extract values there? you can link events to these controls and when they change you get these value and save them. Later on, you can use these values(or array) without accessing cells or retrieving them.

但是,为什么您必须获得整个单元格才能获得一个值?您如何创建几个变量(或者甚至更好,数组)并在那里提取值?您可以将事件链接到这些控件,当它们发生变化时,您可以获得这些值并保存它们。稍后,您可以使用这些值(或数组)而无需访问单元格或检索它们。

EDIT:

编辑:

How about tags? I am not sure if you are adding this through code or storyboard, but I will go through both of them.

标签呢?我不确定您是通过代码还是故事板添加它,但我会同时介绍它们。

In cellForRowAtIndexPath, you can simply say cell.tag = indexPath.row, or even better: cell.tag = question.id( assuming that question is your custom class). That way, you can go through questions and take specific ones.

在 cellForRowAtIndexPath 中,您可以简单地说cell.tag = indexPath.row,甚至更好:(cell.tag = question.id假设该问题是您的自定义类)。这样,您可以浏览问题并选择特定的问题。

Here is working code with tags:

这是带有标签的工作代码:

    @IBAction func test(sender: AnyObject) {
        var lbl : UILabel = self.tableView.viewWithTag(12) as UILabel!
        var cell : UITableViewCell = self.view.viewWithTag(3) as UITableViewCell!
        return ;
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = indexPath.row == 0 ? tableView.dequeueReusableCellWithIdentifier("firstCell", forIndexPath: indexPath) as UITableViewCell : tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) as UITableViewCell
        if(indexPath.row != 0){
        let item = toDoList[indexPath.row-1]

        cell.textLabel?.text = item.title
        NSLog("%d",indexPath.row)
        var integerncina = (indexPath.row + 10) as NSInteger!
        cell.textLabel?.tag = integerncina
        NSLog("%d", cell.textLabel!.tag)
        cell.tag = indexPath.row
        }
        // Configure the cell...

        return cell
    }

回答by kunal pal

I know this is a very old post but then to if it helps someone I'll be happy so to do this the simple way which I will prefer is made an array of the UI table view cell and called it in the UI View Controller and then this becomes very simple just called the array (Thanks to rohan)

我知道这是一篇很老的帖子,但是如果它对某人有帮助,我会很高兴,所以我更喜欢用简单的方法制作 UI 表视图单元格的数组,并在 UI 视图控制器中调用它,然后然后这变得非常简单,只是称为数组(感谢 rohan)

(FOR EXAMPLE)

(例如)

import UIKit


public class PlanningTableView:UITableViewCell{

    @IBOutlet weak var Sccode: UITextField!
    @IBOutlet weak var NoOfPatients: UITextField!

}

(AND NOW IN VIEW CONTROLLER DO THIS)

(现在在视图控制器中执行此操作)

import UIKit

class PlanningReport:UIViewController,UITableViewDelegate,UITableViewDataSource{

    var ScCode = [String]()
    var NoOfPatient = [String]()
    var CollectionOfCell = [PlanningTableView]()


 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
     let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! PlanningTableView
    CollectionOfCell.append(cell)
    return cell
}

//////// Then at sumbmit Button just do this /////////////////

/////// 然后在sumbmit Button 执行此操作////////////////

@IBAction func Submit(_ sender: Any) {

     CollectionOfCell.forEach { cell in
           ScCode.append(cell.Sccode.text!)
           NoOfPatient.append(cell.NoOfPatients.text!)
     }
}

For more details I just created a YouTube first ever tutorial- comments good/bad appreciated

有关更多详细信息,我刚刚创建了一个 YouTube 第一个教程- 评论好/坏赞赏

回答by Lester

To collect data from your cells after the user has finished entering the data (score and level), you can use the UITableViewdelegate method tableView:didDeselectRowAtIndexPath[Deselect]

要在用户完成输入数据(分数和级别)后从您的单元格中收集数据,您可以使用UITableView委托方法tableView:didDeselectRowAtIndexPath[ Deselect]

The code in your instance will go in UITableViewControllerclass and will look something like this.

您实例中的代码将进入UITableViewController课堂,看起来像这样。

override func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
    let cell = tableView.cellForRowAtIndexPath(indexPath) as YourCustomCellClass
    var levelArray:[String] = [] //Assuming you want to collect and store your cell data in an Array. You may use a Dictionary as well, whichever is more convenient.
    var scoreArray:[String] = []
    // levelArray.append(cell.levelLabel.text!)
    // scoreArray.append(cell.scoreLabel.text!)
    levelArray.insert(cell.levelLabel.text!, atIndex: indexPath.row)
    scoreArray.insert(cell.scoreLabel.text!, atIndex: indexPath.row)
}

Next, in you submit button's action(Selector) function use the 'levelArray' and 'scoreArray' to pass your collected data. Be sure to declare the array/dictionary variables(ex: levelArray) right under your UITableViewControllerclass declaration, like so

接下来,在您提交按钮的 action(Selector) 函数中,使用“levelArray”和“scoreArray”来传递您收集的数据。确保在UITableViewController类声明下声明数组/字典变量(例如:levelArray),就像这样

class GpaCalculator: UITableViewController {
    var levelArray:[String] = []
    var scoreArray:[String] = []

    override func viewDidLoad() {
        super.viewDidLoad()
    }
    // ...
}

..to be able to use it in other functions like your submit button's action(Selector) function.

.. 能够在其他功能中使用它,例如提交按钮的操作(选择器)功能。