如何使用Swift将显示的值从Viewcontroller B显示到Viewcontroller A tableview自定义单元格textview?

时间:2019-04-26 06:12:12

标签: swift uiviewcontroller

我的情况是,我正在将值从Viewcontroller B传递到Viewcontroller A。在Viewcontroller A中,我使用CustomCell textview维护表视图(我仅使用一行)。在此文本视图中,我需要显示我从Viewcontroller B那里获得了价值。在这里,下面我正在使用的代码。请针对我的情况提供一些想法。

class ViewcontrollerB: UIViewController, isAbleToReceiveData  {

    func pass(data: String) {
        print("USER: \(data)")
    }

    .... 
    ....   

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = self.tableview.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CustomCell

        // From TextView Placeholder and Color
        cell.from_textview.text = "Enter your text" // here I need to show received “data” from VC_B.
        cell.from_textview.textColor = UIColor.lightGray

        return cell
    }
}

2 个答案:

答案 0 :(得分:1)

创建一个变量,该变量可以从VC_A的任何地方访问

var stringReceived: String? = nil

现在在功能中

func pass(data: String) {
        print("USER: \(data)")
        //add the following 
        stringReceived = data
        self.UITableView_name.reloadData()
    }

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell

将以下内容从cell.from_textview.text = "Enter your text"更改为cell.from_textview.text = stringReceived!

因此,一旦收到数据,基本上使用reloadData()刷新UITableView。

答案 1 :(得分:0)

func pass(data: String) {
    let indexPath = IndexPath.init(row: 0, section: 0)
    let cell = tableView.cellForRow(at: indexPath) as CustomCell
    cell.from_textview.text = data
    }

由于只有1个单元格,因此它将成为第0行第0节,而tableView.reloadData()也将起作用。但是如果您有多个单元格,并且想要更改1个特定的单元格,最好只呼叫该单元格,甚至调用self.tableView.reloadRows(at: [IndexPath], with: UITableViewRowAnimation)

相关问题