簡體   English   中英

將數據(標簽)從TableViewCell傳遞到另一個ViewController

[英]Pass Data (Label) from TableViewCell to another ViewController

我想在單擊單元格時將Label從TableViewCell傳遞給ViewController。 最后,它應該類似於twitter,如果您單擊帶有Label的單元格,則將傳遞帶有相同Label初始化的detailViewController。 我的代碼不起作用,因為我只是從情節提要中獲得了總括性的標簽...

import UIKit
import Firebase

class JobTableViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

@IBOutlet weak var tableView: UITableView!
var valueToPass:String!


 func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
    return true
}

 func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

 func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
    // Arvice return to count jobs
    return jobs.count
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    print("You selected cell #\(indexPath.row)!")

    // Get Cell Label
    let indexPath = tableView.indexPathForSelectedRow!
    let currentCell = tableView.cellForRow(at: indexPath)! as UITableViewCell

    let valueToPass = currentCell.textLabel?.text
    print("value: \(valueToPass)")

    performSegue(withIdentifier: "toDetails", sender: valueToPass)
}

 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
    let cell = tableView.dequeueReusableCell(withIdentifier: "JobCell", for: indexPath) as! JobTableViewCell
    let job = jobs[indexPath.row]
    cell.job = job

    //spacing
    cell.contentView.backgroundColor = UIColor.clear

    let whiteRoundedView : UIView = UIView(frame: CGRect(x: 10, y: 8, width: self.view.frame.size.width - 20, height: 120))

    whiteRoundedView.layer.backgroundColor = CGColor(colorSpace: CGColorSpaceCreateDeviceRGB(), components: [0.36, 0.39, 0.40, 1.0])
    whiteRoundedView.layer.masksToBounds = false
    whiteRoundedView.layer.cornerRadius = 2.0
    whiteRoundedView.layer.shadowOffset = CGSize(width: 0, height: 0)
    whiteRoundedView.layer.shadowOpacity = 0.0

    cell.contentView.addSubview(whiteRoundedView)
    cell.contentView.sendSubview(toBack: whiteRoundedView)

    cell.emojiLabel.text = cell.emojiString

    return cell
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "toDetails" {
        let destinationViewController = segue.destination as! JobDetailViewController
        destinationViewController.valueToPass = (sender as? String)!
    }
}

我的手機:

import UIKit
import Firebase

class JobTableViewCell: UITableViewCell {

@IBOutlet weak var jobLabel: UILabel!

var job: Job! {
    didSet {
        jobLabel.text = job.text
    }
}
}

Job.Swift:

import Foundation
import Firebase

class Job{

var text: String = ""
let ref: DatabaseReference!

init(text: String) {
    self.text = text
    ref = Database.database().reference().child("jobs").childByAutoId()
}

init(snapshot: DataSnapshot)
{
    ref = snapshot.ref
    if let value = snapshot.value as? [String : Any] {
        text = value["text"] as! String
    }
}

func save() {
    ref.setValue(toDictionary())
}

func toDictionary() -> [String : Any]
{
    return [
        "text" : text,
    ]
}
}

在我的DestinationController中:

import UIKit
import Firebase

class JobDetailViewController: UIViewController {

 @IBOutlet weak var jobDetail: RoundText!



var valueToPass: String = ""

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    jobDetail.text = valueToPass
}

override func viewDidLoad() {
    super.viewDidLoad()

    title = "Jobinformation"
}
}

您不應該使用單元格來存儲數據。 您應該具有一個數據模型,該數據模型表示要在單元格中顯示的數據,並且應該使用所選單元格的indexPath在數據模型中查找數據。

快速解決方案:

  1. performSegue(withIdentifier: "yourSegueIdentifer", sender: self)更改為performSegue(withIdentifier: "yourSegueIdentifer", sender: valueToPass)

2.您准備Segue方法應如下所示:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
     if segue.identifier == "yourSegueIdentifer" {
         let destinationViewController = segue.destination as!   AnotherViewController
             destinationViewController.valueToPass = sender as? String
    }
}
  1. 在AnotherViewController上創建var valuteToPass: String = ""並設置您的label.text = valueToPass

但我認為您不應使用currentCell.textLabel.text值,而應使用原始值。 (就像您將currentCell設置為cell.textLabel.cell = array[indexPath.row] ,您的valueToPass應該是valueToPass = array[indexPath.row]

編輯:

您使用didDeselectRowAt方法,而不是didSelectRowAt。

func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath)更改為func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)

不要使用全局變量,請在didSelectRowAt中創建它。

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    print("You selected cell #\(indexPath.row)!")

    // Get Cell Label
    let indexPath = tableView.indexPathForSelectedRow!
    let currentCell = tableView.cellForRow(at: indexPath)! as UITableViewCell

    let valueToPass = currentCell.textLabel?.text
    print("value: \(valuteToPass)")

    performSegue(withIdentifier: "toDetails", sender: valueToPass)
}

在DestinationController上:

class DestinationController: UIViewController {

var valuteToPass: String = ""

  override func viewDidLoad() {
    super.viewDidLoad()
   jobLabel.text = valueToPass
   }

}

編輯2

JobTableViewController

  1. 刪除var valueToPass:String!

更改let valueToPass = jobs[indexPath.row].text而不是let valueToPass = currentCell.textLabel?.text我在您的代碼中檢查了此更改,這將起作用。

嗨,我無法發表評論,但即時通訊使用@Dris答案,但我一直收到此錯誤消息

Could not cast value of type 'UITableViewCell' (0x115464e18) to 'NSString' (0x10fa594c8).

SIGABRT的目標行是destinationViewController.valueToPass = (sender as? String)!

這是為什么?

這基本上是我的代碼

 func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        //  Determine what to do when a cell in a particular section is selected.
        print("did select:      \(indexPath.row)  ")

        // Get Cell Label
        let indexPath = tableView.indexPathForSelectedRow!
        let currentCell = tableView.cellForRow(at: indexPath)! as UITableViewCell

        valueToPass = currentCell.textLabel?.text
        print("valueToPass: \(String(describing: valueToPass))")
        performSegue(withIdentifier: "cellToView", sender: self)

    }

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

        var cell:UITableViewCell?

        if tableView == self.tableView {

            let currentNotif = notificationList[indexPath.row]
            cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as UITableViewCell
            cell?.textLabel?.text = currentNotif.notifType
            cell?.detailTextLabel?.text = "\(currentNotif.notifTime) \n\(currentNotif.notifContent)"
        }

        if tableView == self.tableViewAnnounce {

            let currentAnnounce = announcementList[indexPath.row]
            cell = tableView.dequeueReusableCell(withIdentifier: "cellAnn", for: indexPath) as UITableViewCell
            cell?.textLabel?.text = currentAnnounce.annouceType
            cell?.detailTextLabel?.text = "\(currentAnnounce.annouceTime) \n\(currentAnnounce.annouceContent)"
        }

        return cell!

    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "cellToView" {
            // perform custom segue operation.

            let destinationViewController = segue.destination as! ExtendedAnnouncementViewController
            destinationViewController.valueToPass = (sender as? String)!
        }
    }

我會避免使用全局變量將數據傳遞到目標視圖控制器。 推遲查找,直到准備好傳遞數據為止。

並且,避免使用強制解包,這會導致運行時崩潰。

使用類似這樣的東西:

let segueIdentifier = "yourSegueIdentifer"
let labelDataSource: [String] = ["SomeText"]

func label(forIndexPath indexPath: IndexPath) -> String? {
    let index = indexPath.row
    guard labelDataSource.indices.contains(index) else { return nil }

    return labelDataSource[index]
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    performSegue(withIdentifier: segueIdentifier, sender: indexPath)
}

func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    guard segue.identifier == segueIdentifier,
        let indexPath = sender as? IndexPath,
        let destinationViewController = segue.destination as? AnotherViewController else { return }

    destinationViewController.valuePassed = label(forIndexPath: indexPath)
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM