首页 > 解决方案 > textView 中数组中的文本(在 TableCell 中)

问题描述

我有一个 UITableView,它将数据(图像和标签)从 Cell 传递到 DetailViewController。这适用于我拥有的所有 20 个单元格!

但是现在我尝试在我的 DetailViewController 中创建一个数组,它给我一个“Comm1Description”和“Comm1Description”(只是来自“arr2”的简单文本)。Comm1Description 用于 Cell1,Comm2Description 用于 Cell2 等。

这是我的代码

import UIKit

 class WCommanderController: UIViewController {

@IBOutlet weak var tbl: UITableView!

var arr = ["Commander1", "Commander2"]
var arr2 = ["Comm1Description", "Comm2Description"]

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}
}

extension WCommanderController: UITableViewDataSource,   UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return arr.count
}


func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return 130
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as? DataTableViewCell
    cell?.img.image = UIImage(named: arr[indexPath.row])
    cell?.lbl.text = arr[indexPath.row]
    return cell!
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let vc = storyboard?.instantiateViewController(withIdentifier: "DetailViewController") as? DetailViewController
    vc?.str = arr[indexPath.row]
    navigationController?.pushViewController(vc!, animated: true)

   }
 }

标签: swift

解决方案


如果您的表格单元中有一个文本视图,那么可以这样做。

let dictionary1 = ["KeyCommander": "Commander1", "KeyDescription": "Comm1Description1", "KeyTextField": "TextField1"]

let dictionary2 = ["KeyCommander": "Commander2", "KeyDescription": "Comm1Description2", "KeyTextField": "TextField2"]

现在,将您的数组设为 var。

var array = [dictionary1, dictionary2]

在 CellForRowAtIndex 上,给文本字段一个标签。

 array[textfield.tag]["KeyTextField"] = "Typed Value"

推荐阅读