本文介绍了在 Swift 中将数据从 tableView 传递到 ViewController的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个应用程序,我正在尝试完全按照我想要的方式进行调整

我一直在关注 Seemu Apps 的 Youtube 教程来制作它,但我需要完成它添加一个可选的 ViewController

此应用程序有 2 个 tableViews 显示车辆,如果我们单击第一个 tableView 的一行,则第二个 tableView 将向我们显示选定车辆的列表.

这是我们到现在为止所拥有的:(图片链接,因为我在 stackOverFlow 上还没有获得 10 分的声誉)

http://subefotos.com/ver/?65ba467040cb9280e8ec49644a.pd>

一切运行正常,但我希望能够在可选的 detailViewController(带有每辆车的详细描述和更大图像的标签)中显示信息,具体取决于我们在 secondTableViewControlle(或应用程序)正是我在 tableViews 之间的教程中遵循的方式

我知道我们需要通过 prepareForSegue 方法传递数据,我已经理解了本教程中的步骤,但是当我们有 2 个 tableviewControllers

例如:如果我们想显示一个带有法拉利 458 信息和这辆车的精美图片的最后一个视图控制器

我们究竟需要做什么才能显示每辆车的信息?

PD:我是编程领域的初学者,也许我需要以一种非常简单的方式来看待它

完整代码:

ViewController.swift导入 UIKit类视图控制器:UIViewController、UITableViewDelegate、UITableViewDataSource {var selMake = String()@IBOutlet var tableView:UITableView!var transportData : [String] = ["Car", "Plane", "Motorcycle", "Truck", "Train", "Bicycle", "Helicopter"]///////////////////////////////////////////viewDidLoad覆盖 func viewDidLoad() {super.viewDidLoad()//注册自定义单元格var nib = UINib(nibName: "customCell", bundle: nil)tableView.registerNib(nib, forCellReuseIdentifier: "cell")}//Section中的行数func tableView(tableView: UITableView, numberOfRowsInSection 部分: Int) ->整数{返回 self.transportData.count}//cellForRowAtIndexPathfunc tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) ->UITableViewCell {/////静态单元格(对自定义单元格无效)/*var cell : UITableViewCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCellcell.textLabel?.text = self.transportData[indexPath.row]返回单元格*/var cell:customCellTableViewCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as customCellTableViewCellcell.lblTrans.text = transportData[indexPath.row]cell.imgTrans.image = UIImage(命名:transportData[indexPath.row])返回单元格}//高度func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) ->CGFloat {返回 90}//didSelectRowAtIndexPathfunc tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {println("Fila \(transportData[indexPath.row]) seleccionada")selMake = transportData[indexPath.row]performSegueWithIdentifier("modelView", sender: self)}覆盖 func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {if(segue.identifier == "modelView") {var vc = segue.destinationViewController 作为 modelViewViewControllervc.selMake = selMake}}导入 UIKit类 customCellTableViewCell: UITableViewCell {@IBOutlet 弱变量 imgTrans:UIImageView!@IBOutlet 弱变量 lblTrans:UILabel!覆盖 funcawakeFromNib() {super.awakeFromNib()//初始化代码}覆盖 func setSelected(selected: Bool, 动画: Bool) {super.setSelected(选中,动画:动画)//为选中状态配置视图}}导入 UIKitclass modelViewViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {///////////////////////////////////var selMake = String()var tableData : [字符串] = []@IBOutlet var tableView:UITableView!///////////////////////////////////覆盖 func viewDidLoad() {super.viewDidLoad()//注册自定义单元格var nib = UINib(nibName: "customCell2", bundle: nil)tableView.registerNib(nib, forCellReuseIdentifier: "cell")切换 selMake {案例汽车":tableData = [法拉利 458",法拉利"]案例飞机":tableData = [伊比利亚"]案例摩托车":tableData = [川崎忍者",雅马哈 Aerox"]案例卡车":tableData = [ "Camion transporte"]案例火车":tableData = [大街"]案例自行车":tableData = ["BMX"]案例直升机":tableData = ["直升机战斗"]默认:println("Sel Make \(selMake)")}self.tableView.reloadData()}覆盖 func didReceiveMemoryWarning() {super.didReceiveMemoryWarning()//处理任何可以重新创建的资源.}func tableView(tableView: UITableView, numberOfRowsInSection 部分: Int) ->整数{返回 self.tableData.count}func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) ->UITableViewCell {/* var cell : UITableViewCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCellcell.textLabel?.text = self.tableData[indexPath.row]返回单元格*/var cell:customCell2TableViewCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as customCell2TableViewCellcell.lbl2text.text = self.tableData[indexPath.row]cell.img2image.image = UIImage (named: tableData[indexPath.row])返回单元格}func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {println("Row \(indexPath.row)selected")performSegueWithIdentifier("detailView", sender: self)}func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) ->CGFloat {返回 90}覆盖 func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {if(segue.identifier == "detailView") {var vc = segue.destinationViewController 作为 DetailViewController}}导入 UIKit类 customCell2TableViewCell: UITableViewCell {@IBOutlet var lbl2text:UILabel!@IBOutlet var img2image:UIImageView!覆盖 funcawakeFromNib() {super.awakeFromNib()//初始化代码}覆盖 func setSelected(selected: Bool, 动画: Bool) {super.setSelected(选中,动画:动画)//为选中状态配置视图}}导入 UIKit类 DetailViewController: UIViewController {@IBOutlet var imgDetail:UIImageView!@IBOutlet var lblDetail:UILabel!覆盖 func viewDidLoad() {super.viewDidLoad()//加载视图后进行任何其他设置.}

试试这个.

ModelViewViewController

var selectedImage:String?var selectedLabel:String?func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {println("Row \(indexPath.row)selected")selectedImage = self.tableData[indexPath.row]selectedLabel = self.tableData[indexPath.row]performSegueWithIdentifier("detailView", sender: self)}覆盖 func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {if(segue.identifier == "detailView") {var vc = segue.destinationViewController 作为 DetailViewControllervc.img = selectedImagevc.lblDetail = selectedLabel}}类 DetailViewController: UIViewController {@IBOutlet var imgDetail:UIImage!@IBOutlet var lblDetail:UILabel!var img:字符串?覆盖 func viewDidLoad() {super.viewDidLoad()//加载视图后进行任何其他设置.imgDetail = UIImage(named: img)}

这应该有效.

I have an App that i'm trying to adapt exactly how i want

I have been following a Youtube tutorial of Seemu Apps to make it but I need to finish it adding an optional ViewController

This app has 2 tableViews showing vehicles and if we click in one row of the first tableView then second tableView will show us a list of selected vehicles.

Here is what we have until now: (image link , because i haven't got ten points reputation on stackOverFlow)

http://subefotos.com/ver/?65ba467040cb9280e8ec49644fd156afo.jpg

All is running perfect, but i want to be able to display information in an optional detailViewController (label with a detailed description of each vehicle and a bigger image of this ) depending of which vehicle we click in the secondTableViewControlle (or modelViewController in the App) exactly how i was following in the tutorial between tableViews

i know that we need to passing data through prepareForSegue method , i have understood this making the steps in the tutorial but when we have 2 tableviewControllers

For example : if we want to display a last viewController with information of Ferrari 458 and a great picture of this car

What do we need to do exactly to show information of each vehicle?

PD : I'm beginner in the programming world, maybe i would need to see it in a very simple way

The whole code:

ViewController.swift

import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

     var selMake = String()

     @IBOutlet var tableView : UITableView!

    var transportData : [String] = ["Car", "Plane", "Motorcycle", "Truck" , "Train", "Bicycle" , "Helicopter"]

    //////////////////////////////////////////

    //viewDidLoad
    override func viewDidLoad() {
        super.viewDidLoad()
        //Register custom cell

        var nib = UINib(nibName: "customCell", bundle: nil)
        tableView.registerNib(nib, forCellReuseIdentifier: "cell")
    }

    //Numbers of rows in Section
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.transportData.count
    }

    //cellForRowAtIndexPath
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        ///// Static Cell (no valid for custom cells)

        /*
        var cell : UITableViewCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell

        cell.textLabel?.text = self.transportData[indexPath.row]

        return cell
        */

        var cell:customCellTableViewCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as customCellTableViewCell

        cell.lblTrans.text = transportData[indexPath.row]
        cell.imgTrans.image = UIImage (named: transportData[indexPath.row])

        return cell
    }

    //height
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {

        return 90
    }

    //didSelectRowAtIndexPath
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        println("Fila \(transportData[indexPath.row]) seleccionada")
        selMake = transportData[indexPath.row]
        performSegueWithIdentifier("modelView", sender: self)
    }

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

        if(segue.identifier == "modelView") {
            var vc = segue.destinationViewController as modelViewViewController
            vc.selMake = selMake
        }
    }

import UIKit

class customCellTableViewCell: UITableViewCell {
    @IBOutlet weak var imgTrans: UIImageView!
    @IBOutlet weak var lblTrans: UILabel!

    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
    }
}

import UIKit

class modelViewViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    //////////////////////////////////
    var selMake = String()
    var tableData : [String] = []
    @IBOutlet var tableView: UITableView!

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

        //Register custom cell

        var nib = UINib(nibName: "customCell2", bundle: nil)
        tableView.registerNib(nib, forCellReuseIdentifier: "cell")

        switch selMake {

        case "Car" :
            tableData = ["Ferrari 458", "La Ferrari"]

        case "Plane" :
            tableData = ["Iberia"]

        case "Motorcycle" :
            tableData = ["Kawasaki Ninja", "Yamaha Aerox"]

        case "Truck" :
            tableData = [ "Camion transporte"]

        case "Train" :
            tableData = [ "Ave" ]

        case "Bicycle" :
            tableData = ["BMX"]

        case "Helicopter" :
            tableData = ["HelicopteroCombate"]

        default:
            println("Sel Make \(selMake)")
        }
        self.tableView.reloadData()
    }

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

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

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

       /* var cell : UITableViewCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell

        cell.textLabel?.text = self.tableData[indexPath.row]

        return cell*/

        var cell:customCell2TableViewCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as customCell2TableViewCell

        cell.lbl2text.text = self.tableData[indexPath.row]
        cell.img2image.image = UIImage (named: tableData[indexPath.row])

        return cell
    }

    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        println("Row \(indexPath.row)selected")

        performSegueWithIdentifier("detailView", sender: self)
    }

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

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


        if(segue.identifier == "detailView") {
            var vc = segue.destinationViewController as DetailViewController
        }
    }

import UIKit

class customCell2TableViewCell: UITableViewCell {
    @IBOutlet var lbl2text: UILabel!

    @IBOutlet var img2image: 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
    }
}

import UIKit
class DetailViewController: UIViewController {
    @IBOutlet var imgDetail: UIImageView!
    @IBOutlet var lblDetail: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }
解决方案

Try this.

ModelViewViewController

var selectedImage:String?
var selectedLabel:String?

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        println("Row \(indexPath.row)selected")
        selectedImage = self.tableData[indexPath.row]
        selectedLabel = self.tableData[indexPath.row]
        performSegueWithIdentifier("detailView", sender: self)
    }

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


        if(segue.identifier == "detailView") {
            var vc = segue.destinationViewController as DetailViewController
           vc.img = selectedImage
           vc.lblDetail = selectedLabel
        }
    }

class DetailViewController: UIViewController {
    @IBOutlet var imgDetail: UIImage!
    @IBOutlet var lblDetail: UILabel!
    var img:String?

override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.

      imgDetail = UIImage(named: img)
    }

This should work.

这篇关于在 Swift 中将数据从 tableView 传递到 ViewController的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 04:07