草庐IT

swift - 在 Swift 中将数据从 tableView 传递到 ViewController

coder 2023-09-04 原文

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

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

此应用程序有 2 个显示车辆的 tableView,如果我们单击第一个 tableView 的一行,那么第二个 tableView 将向我们显示所选车辆的列表。

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

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

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

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

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

我们具体需要做什么来显示每辆车的信息?

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

完整代码:

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

最佳答案

试试这个。

模型 View View Controller

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

这应该有效。

关于swift - 在 Swift 中将数据从 tableView 传递到 ViewController,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28051631/

有关swift - 在 Swift 中将数据从 tableView 传递到 ViewController的更多相关文章

  1. ruby-on-rails - 在 Rails 中将文件大小字符串转换为等效千字节 - 2

    我的目标是转换表单输入,例如“100兆字节”或“1GB”,并将其转换为我可以存储在数据库中的文件大小(以千字节为单位)。目前,我有这个:defquota_convert@regex=/([0-9]+)(.*)s/@sizes=%w{kilobytemegabytegigabyte}m=self.quota.match(@regex)if@sizes.include?m[2]eval("self.quota=#{m[1]}.#{m[2]}")endend这有效,但前提是输入是倍数(“gigabytes”,而不是“gigabyte”)并且由于使用了eval看起来疯狂不安全。所以,功能正常,

  2. ruby - 解析 RDFa、微数据等的最佳方式是什么,使用统一的模式/词汇(例如 schema.org)存储和显示信息 - 2

    我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i

  3. ruby - Ruby 有 `Pair` 数据类型吗? - 2

    有时我需要处理键/值数据。我不喜欢使用数组,因为它们在大小上没有限制(很容易不小心添加超过2个项目,而且您最终需要稍后验证大小)。此外,0和1的索引变成了魔数(MagicNumber),并且在传达含义方面做得很差(“当我说0时,我的意思是head...”)。散列也不合适,因为可能会不小心添加额外的条目。我写了下面的类来解决这个问题:classPairattr_accessor:head,:taildefinitialize(h,t)@head,@tail=h,tendend它工作得很好并且解决了问题,但我很想知道:Ruby标准库是否已经带有这样一个类? 最佳

  4. ruby - rails 3 redirect_to 将参数传递给命名路由 - 2

    我没有找到太多关于如何执行此操作的信息,尽管有很多关于如何使用像这样的redirect_to将参数传递给重定向的建议:action=>'something',:controller=>'something'在我的应用程序中,我在路由文件中有以下内容match'profile'=>'User#show'我的表演Action是这样的defshow@user=User.find(params[:user])@title=@user.first_nameend重定向发生在同一个用户Controller中,就像这样defregister@title="Registration"@user=Use

  5. ruby-on-rails - 如何生成传递一些自定义参数的 `link_to` URL? - 2

    我正在使用RubyonRails3.0.9,我想生成一个传递一些自定义参数的link_toURL。也就是说,有一个articles_path(www.my_web_site_name.com/articles)我想生成如下内容:link_to'Samplelinktitle',...#HereIshouldimplementthecode#=>'http://www.my_web_site_name.com/articles?param1=value1¶m2=value2&...我如何编写link_to语句“alàRubyonRailsWay”以实现该目的?如果我想通过传递一些

  6. ruby - 我如何添加二进制数据来遏制 POST - 2

    我正在尝试使用Curbgem执行以下POST以解析云curl-XPOST\-H"X-Parse-Application-Id:PARSE_APP_ID"\-H"X-Parse-REST-API-Key:PARSE_API_KEY"\-H"Content-Type:image/jpeg"\--data-binary'@myPicture.jpg'\https://api.parse.com/1/files/pic.jpg用这个:curl=Curl::Easy.new("https://api.parse.com/1/files/lion.jpg")curl.multipart_form_

  7. 世界前沿3D开发引擎HOOPS全面讲解——集3D数据读取、3D图形渲染、3D数据发布于一体的全新3D应用开发工具 - 2

    无论您是想搭建桌面端、WEB端或者移动端APP应用,HOOPSPlatform组件都可以为您提供弹性的3D集成架构,同时,由工业领域3D技术专家组成的HOOPS技术团队也能为您提供技术支持服务。如果您的客户期望有一种在多个平台(桌面/WEB/APP,而且某些客户端是“瘦”客户端)快速、方便地将数据接入到3D应用系统的解决方案,并且当访问数据时,在各个平台上的性能和用户体验保持一致,HOOPSPlatform将帮助您完成。利用HOOPSPlatform,您可以开发在任何环境下的3D基础应用架构。HOOPSPlatform可以帮您打造3D创新型产品,HOOPSSDK包含的技术有:快速且准确的CAD

  8. ruby - 在 Ruby 中按名称传递函数 - 2

    如何在Ruby中按名称传递函数?(我使用Ruby才几个小时,所以我还在想办法。)nums=[1,2,3,4]#Thisworks,butismoreverbosethanI'dlikenums.eachdo|i|putsiend#InJS,Icouldjustdosomethinglike:#nums.forEach(console.log)#InF#,itwouldbesomethinglike:#List.iternums(printf"%A")#InRuby,IwishIcoulddosomethinglike:nums.eachputs在Ruby中能不能做到类似的简洁?我可以只

  9. FOHEART H1数据手套驱动Optitrack光学动捕双手运动(Unity3D) - 2

    本教程将在Unity3D中混合Optitrack与数据手套的数据流,在人体运动的基础上,添加双手手指部分的运动。双手手背的角度仍由Optitrack提供,数据手套提供双手手指的角度。 01  客户端软件分别安装MotiveBody与MotionVenus并校准人体与数据手套。MotiveBodyMotionVenus数据手套使用、校准流程参照:https://gitee.com/foheart_1/foheart-h1-data-summary.git02  数据转发打开MotiveBody软件的Streaming,开始向Unity3D广播数据;MotionVenus中设置->选项选择Unit

  10. 使用canal同步MySQL数据到ES - 2

    文章目录一、概述简介原理模块二、配置Mysql使用版本环境要求1.操作系统2.mysql要求三、配置canal-server离线下载在线下载上传解压修改配置单机配置集群配置分库分表配置1.修改全局配置2.实例配置垂直分库水平分库3.修改group-instance.xml4.启动监听四、配置canal-adapter1修改启动配置2配置映射文件3启动ES数据同步查询所有订阅同步数据同步开关启动4.验证五、配置canal-admin一、概述简介canal是Alibaba旗下的一款开源项目,Java开发。基于数据库增量日志解析,提供增量数据订阅&消费。Git地址:https://github.co

随机推荐