简体   繁体   English

快速比较不同行中的两个标签

[英]Compare two labels from different rows in swift

say me, please, how better compare two same (label has name "labelNumber") labels from different rows in Tableview 请问我,如何更好地比较Tableview中不同行中的两个相同(标签具有名称“ labelNumber”)标签

For example: I know, that in row №0 label is "06" (Int) and in next cell (row №1) this label is "07". 例如:我知道,在第0行的标签是“ 06”(整数),在下一个单元格(第1行)中的标签是“ 07”。 So, "07" > "06". 因此,“ 07”>“ 06”。 How compare it with swift language? 如何与快速语言进行比较?

Thanks! 谢谢!

Compare the values stored within your data array: 比较存储在数据数组中的值:

if dataArray[0].myIntegerValue > dataArray[1].myIntegerValue {
    // Do your stuff
}

Edit: this assumes your data is stored as objects with that Int as an attribute. 编辑:这假定您的数据存储为该Int作为属性的对象。

As the others have said, don't do that. 正如其他人所说,不要那样做。 In the MVC design pattern, labels are views. 在MVC设计模式中,标签是视图。 They are for displaying data, not storing it. 它们用于显示数据,而不是存储数据。

Trying to read values from table view labels is especially bad, because as the table view scrolls, the cells that go off-screen will be recycled and the values in their views will be discarded. 尝试从表视图标签中读取值特别糟糕,因为当表视图滚动时,屏幕外的单元格将被回收并且其视图中的值将被丢弃。 You need to save your data to a model object. 您需要将数据保存到模型对象。 (An array works just fine to save table view data, or an array of arrays for a sectioned table view.) (数组可以很好地保存表视图数据,而数组可以用于分段表视图。)

The wrong way 错误的方法

As stated by @vadian , you should NOT use the UI you populated to perform calculations on data. @vadian所述 ,您不应使用填充的UI对数据执行计算。

However this is the code to compare the values inside 2 UITableViewCell(s) 但这是用于比较2个UITableViewCell(s)的值的代码

class Controller: UITableViewController {

    func equals(indexA: NSIndexPath, indexB: NSIndexPath) -> Bool? {
        guard let
            cellA = tableView.cellForRowAtIndexPath(indexA),
            cellB = tableView.cellForRowAtIndexPath(indexB) else { return nil }

        return cellA.textLabel?.text == cellB.textLabel?.text
    }
}

The right way 正确的方式

Think about how you are populating the cells. 考虑一下您如何填充单元格。 I imagine you are using some Model Value. 我想您正在使用某些模型值。 So just compare the Model Values you are using to populate the cells. 因此,只需比较用于填充单元格的模型值即可。

Probably something like this 大概是这样的

class Controller: UITableViewController {

    var data: [Int] = [] // ....

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        guard let cell = tableView.dequeueReusableCellWithIdentifier("YourCellID") else { fatalError("No cell found with this id: 'YourCellID'")}
        cell.textLabel?.text = String(data[indexPath.row])
        return cell
    }

    func equals(indexA: NSIndexPath, indexB: NSIndexPath) -> Bool? {
        return data[indexA.row] == data[indexB.row]
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM