Wyślij dane z TableView do DetailView Swift

Staram się zrobić może jedną z najprostszych i bardziej mylących rzeczy dla mnie do tej pory Chcę stworzyć własną aplikację i aby to zrobić, muszę być w stanie przekazać pewne informacje w zależności od tego, który wiersz użytkownik kliknie (to szybka długość)

Mamy RootViewController (widok tabeli) i DetailViewController (z 1 etykietą i 1 obrazem) Tutaj wpisz opis obrazka

(nasz pogląd)

Oto kod:

@IBOutlet weak var tableView: UITableView!


var vehicleData : [String] = ["Ferrari 458" , "Lamborghini Murcielago" , "Bugatti Veyron", "Mercedes Benz Biome"]

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

    var nib = UINib(nibName: "TableViewCell", bundle: nil)

    tableView.registerNib(nib, forCellReuseIdentifier: "cell")



}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return vehicleData.count
}



func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {


    let cell:TableViewCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as TableViewCell

    cell.lblCarName.text = vehicleData[indexPath.row]

    cell.imgCar.image = UIImage(named: vehicleData[indexPath.row])

    return cell   
}

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

    performSegueWithIdentifier("DetailView", sender: self)
}

 override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

    if(segue.identifier == "DetailView") {

        var vc = segue.destinationViewController as DetailViewController

    }

}

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    return 100
}

Własna Klasa TableViewCell (posiada plik xib z cell)

class TableViewCell: UITableViewCell {


@IBOutlet weak var lblCarName: UILabel!

@IBOutlet weak var imgCar: UIImageView!

override func awakeFromNib() {
    super.awakeFromNib()
    // Initialization code
}

override func setSelected(selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)

    // Configure the view for the selected state
}

class DetailViewController: UIViewController {



    @IBOutlet weak var lblDetail: UILabel!

    @IBOutlet weak var imgDetail: UIImageView!

    override func viewDidLoad() {
        super.viewDidLoad()
    }

Pytanie brzmi:

Jeśli użytkownik kliknie Ferrari 458, lblDetail w Szczegółachviewcontroller pokaże: Ferrari 458 to super samochód, który jest w stanie osiągnąć 325 km/ h ...... (cokolwiek chcemy) i imgDetail byłby w stanie pokazać obraz (cokolwiek chcemy) samochodu

Jeśli użytkownik kliknie Bugatti Veyron teraz lblDetail pokaż nam: Bugatti Veyron to doskonała i super sportowa maszyna. To jeden z najszybszych samochodów na świecie....

ImgDetail pokaż nam zdjęcie ten samochód

To samo ze wszystkimi samochodami w zależności od tego, który rząd kliknęliśmy

Wiem, że praca jest wokół preparedforsegue func w first View Controller, ale próbowałem wiele różnych sposobów, aby to było możliwe i wszystko działa ok

Jak możemy to zrobić???
Author: Christian, 2015-02-10

4 answers

Oto przykład dla Ciebie:

var valueToPass:String!

func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
    println("You selected cell #\(indexPath.row)!")

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

    valueToPass = currentCell.textLabel.text
    performSegueWithIdentifier("yourSegueIdentifer", sender: self)
}

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?){

    if (segue.identifier == "yourSegueIdentifer") {
        // initialize new view controller and cast it as your view controller
        var viewController = segue.destinationViewController as AnotherViewController
        // your new view controller should have property that will store passed value
        viewController.passedValue = valueToPass
    }
}

Ale nie zapomnij utworzyć zmiennej passedValue w swoim DetailViewController.

Jest to tylko przykład przekazywania danych z jednego kontrolera viewController do drugiego i możesz przekazać dane za pomocą tego przykładu zgodnie z potrzebami.

I więcej informacji na ten link.

Przekazywanie wartości między kontrolerami widoku na podstawie wyboru listy w języku Swift

Stosować diselectrowatindexpath lub preparedforsegue method for UITableView?

Swift: przekazać Etykietę UITableViewCell do nowego Viewcontrollera

Https://teamtreehouse.com/forum/help-swift-segue-with-variables-is-not-working

Może to ci pomoże.

Swift 3.0

var valueToPass:String!
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

    valueToPass = currentCell.textLabel?.text
    performSegue(withIdentifier: "yourSegueIdentifer", sender: self)
}

func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?){

    if (segue.identifier == "yourSegueIdentifer") {
        // initialize new view controller and cast it as your view controller
        var viewController = segue.destination as! AnotherViewController
        // your new view controller should have property that will store passed value
        viewController.passedValue = valueToPass
    }
}
 37
Author: Dharmesh Kheni,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:03:02

Jeśli przeciągniesz segue z komórki prototypu (w Konstruktorze interfejsu) do następnego kontrolera widoku i ustawisz jego identyfikator segue na "Twój Identyfikator Segue", możesz to zrobić również za pomocą tego skrótu:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "Your Segue Identifier" {
        let cell = sender as! YourCustomCell
        let vc = segue.destination as! PushedViewController
        vc.valueToPass = cell.textLabel?.text // or custom label
    }
}

I nie potrzebujesz również performSegueWithIdentifier() w didSelectRowAtIndexPath(), ani tej metody widoku tabeli.

W PushedViewController.swift (następny kontroler widoku):

var valueToPass: String!

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

Ważne jest, aby ustawić wartość etykiety po zainicjowaniu jej z storyboardu. Oznacza to, że nie można ustawić etykiety w poprzedni kontroler widoku jest bezpośrednio prepareForSegue(), dlatego musi go przekazać valueToPass.

 1
Author: Teodor Ciuraru,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-03-04 08:15:05

Może to być inne rozwiązanie, bez większego kodu w metodzie didSelectRowAtIndexPath. Zauważ, że chociaż może to wyglądać na czystsze i nie potrzebujemy dodatkowej zmiennej valueToPass, może to nie być najlepsza praktyka, ponieważ argument sender wewnątrz metody performSegue ma być rzeczywistym obiektem, który zainicjował segue (lub nil).

// MARK: UITableViewDelegate methods

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    tableView.deselectRow(at: indexPath, animated: true)

    performSegue(withIdentifier: "goToSecondVC", sender: indexPath)
}

// MARK: UIViewController methods

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "goToSecondVC" {    
        if segue.destination.isKind(of: CarDetailsController.self) {
            let secondVC = segue.destination as! CarDetailsController

            let indexPath = sender as! IndexPath

            secondVC.passedValue = carsArray[indexPath.row]
        }
    }
}
 1
Author: ppalancica,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-08-23 15:04:53

Its simple, am adding one statement to above answer. Aby uzyskać nazwę wybranego samochodu w widoku szczegółów,

LblDetail.text = passedValue

Możesz dodać ten kod linii w funkcji viewDidLoad () w widoku szczegółowym. passedValue zawiera nazwę samochodu, który użytkownik wybrał (przypisać w prepareForSegue), a następnie można przypisać do etykiety detailedView.

Mam nadzieję, że to pomoże!!

 0
Author: Pruthvi Hariharan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-05-04 20:24:02