简体   繁体   English

通用函数不会在tableView.reloadData()之后更新tableview单元格中的label的值

[英]Generic function does not update the value of label in tableview cell after tableView.reloadData()

I have a function where I am incrementing the value of the label as below 我有一个函数,在其中我增加标签的值,如下所示

@IBAction func buttonClicked(_ sender: UIButton) {
        let indexPath = indexPath(sender: sender, tableView: profileTableView)

        array[Int((indexPath.row))].likes = String(Int(array[Int((indexPath.row))].likes)!+1)
        self.userProfileTableView.reloadData()
    } 

In the above function after the reloadData value of the label gets incremented to the next number, But when I make it a generic function in an extension as below the value of the label does not increment 在上面的函数中,标签的reloadData值增加到下一个数字后,但是当我在扩展名中将其设为通用函数时,如下所示,标签的值不会增加

func buttonClicked(data:String,tableView:UITableView) {
        let data = String(Int(data)!+1)
        print("Incremented data", data)
        tableView.reloadData()
    }

I am calling the function as following but the label does not get updated with the incremented value . 我正在按以下方式调用该函数,但标签未使用增量值进行更新。 It retains the old value. 它保留了旧的价值。

buttonClicked(data: feeds[Int((indexPath.row))].likes, tableView: userProfileTableView)

Any help will be appreciated . 任何帮助将不胜感激 。 Thank you. 谢谢。

you should change your code to this. 您应该将代码更改为此。

let numLikes = Int(feeds[Int((indexPath.row))].likes)!
feeds[Int((indexPath.row)).likes = String(numLikes)

Because String is a value types. 因为String是一个值类型。

When you do this. 当您这样做时。

buttonClicked(data: feeds[Int((indexPath.row))].likes, tableView: userProfileTableView)

func buttonClicked(data:String,tableView:UITableView) {
    let data = String(Int(data)!+1)
    print("Incremented data", data)
    tableView.reloadData()
}

1) New value variables data in func buttonClicked will be created and has value = feeds[Int((indexPath.row))].likes 1)将创建func buttonClicked新值变量data ,并具有value = feeds[Int((indexPath.row))].likes

2) when you change data , it just change data but not feeds[Int((indexPath.row))].likes 2)当您更改data ,它只是更改data而不是feeds[Int((indexPath.row))].likes

Look at Value and Reference Type for more info. 查看值和引用类型以获取更多信息。

Actually You didn't update the array object with updated value in your generic method. 实际上,您没有在通用方法中使用更新后的值来更新数组对象。

Either you may have to update the incremented value in array OR send your array to the generic function with selected index. 您可能必须更新数组中的增量值,或者将数组发送给具有选定索引的通用函数。

Example: 例:

func buttonClicked(feeds:[Feed], index:Int, tableView:UITableView) {

        feeds[index].likes = String(Int(feeds[index].likes)!+1)
        tableView.reloadData()
    }

But I don't say this as generic function, since It's using for minimal places with minimal code and there is no generic types to reuse. 但是我没有说这是泛型函数,因为它用于最少的地方,具有最少的代码,并且没有可重用的泛型类型。

Thanks! 谢谢!

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

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