gpt4 book ai didi

swift - 将数据从 TableViewCell 标签传递到 ViewController

转载 作者:行者123 更新时间:2023-11-30 13:30:33 25 4
gpt4 key购买 nike

项目:https://github.com/vpags1/events.git

我需要将数据从 TableView 传递到 ViewController。数据显示在带有两个标签和 UIIMage(名称、详细信息、照片)的单元格上,单击该标签会将您带到另一个详细信息 View Controller ,该 Controller 显示信息。

我现在的情况是,数据存储在 View Controller 中的三个数组中,但是当我与教授交谈时,他告诉我,最简单的方法是将数据存储在单独的文件中。我真的不知道如何实现这一点,无论是方式还是其他方法,我都将不胜感激。

import UIKit

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

var names = ["Brown Diner", "Kirkland", "Choco", "Lil Wayne", "Annie", "Social"]
var details = ["Free drink with meal after 12 AM", "LADIES drink free", "10% off all ice cream!", "concert", "a Theater Production", "Bring your Squad to the Social"]
var images = [UIImage(named: "brown"), UIImage(named: "kirk"), UIImage(named: "choco"), UIImage(named: "lilwayne"), UIImage(named: "default"), UIImage(named: "default")]

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

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = self.eventsTable.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! CustomCell

cell.name.text = names[indexPath.row]
cell.detail.text = details[indexPath.row]
cell.photo.image = images[indexPath.row]
return cell
}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.names.count
}
//
// override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
//
// if segue.identifier == "detailsSegue" {
// guard let eventVC = segue.destinationViewController as? DetailsViewController,
// let eventIndex = tableView.indexPathForSelectedRow?.row else {
// return
// }
// eventVC.eventName = names[eventIndex]
// eventVC.eventDetail = details[eventIndex]
// eventVC.eventPhoto = images[eventIndex]
// }
//
// }
}

我的详细信息ViewController

import UIKit

class DetailsViewController : UIViewController {

@IBOutlet var detailsLabel: UILabel!
@IBOutlet var detailsImage: UIImageView!
@IBOutlet var detailsDesc: UILabel!

override func viewDidLoad() {

}
}

我的 CustomCell.swift 文件

import UIKit

class CustomCell: UITableViewCell {

@IBOutlet var photo: UIImageView!
@IBOutlet var name: UILabel!
@IBOutlet var detail: 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
}

}

我对 Swift 非常陌生,事实证明它对我来说非常具有挑战性。我确实不是编码员,但是项目要求我完成我作为 UI/UIX 设计师的应用程序的一些编码。提前感谢您的帮助!

最佳答案

您可以使用数组中的数据创建一个 JSON 文件并将其添加到您的项目中:

{
"events":[
{
"name": "BTown Diner",
"details": "Free drink with meal after 12 AM",
"image": "btown"
},
{
"name": "Dunnkirk",
"details": "LADIES drink free",
"image": "dunn"
},
{
"name": "Chocolate Mousse",
"details": "10% off all ice cream!",
"image": "choco"
},
{
"name": "Lil Wayne",
"details": "Lil 500 concert",
"image": "lilwayne"
},
{
"name": "Annie",
"details": "an IU Theater Production",
"image": "default"
},
{
"name": "Campus Squad Social",
"details": "Bring your Squad to the Campus Squad Social",
"image": "default"
},
]
}

创建一个 Event 类来封装单个事件的数据:

import UIKit

class Event {

let name: String!
let details:String!
let image: UIImage!

init(eventData: [String: String])
{
self.name = eventData["name"]
self.details = eventData["details"]
self.image = UIImage(named: eventData["image"]!)
}
}

将事件类型的属性添加到您的DetailsViewController:

import UIKit

class DetailsViewController : UIViewController {

// To get the event from the main view controller
var event: Event!


@IBOutlet var detailsLabel: UILabel!
@IBOutlet var detailsImage: UIImageView!
@IBOutlet var detailsDesc: UILabel!

override func viewDidLoad() {

detailsLabel.text = event.name
detailsDesc.text = event.details
detailsImage.image = event.image
}
}

将类事件数组添加到主 ViewController读取 ViewDidLoad 中的 JSON 数据并填充您的 events 数组实现prepareForSegue并使用所选事件设置DetailsViewController的event属性。

import UIKit

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

@IBOutlet var tableView: UITableView!

// Created an Event class to store the event data
// Moved the hard coded data to Events.json
var events = [Event]()

override func viewDidLoad() {
super.viewDidLoad()

// Read the JSON data from main bundle
if let path = NSBundle.mainBundle().pathForResource("Events", ofType: "json") {
do {
let jsonData = try NSData(contentsOfFile: path, options: NSDataReadingOptions.DataReadingMappedIfSafe)
let parsedData = parseJSON(jsonData); // parse data to Swift dictionary
print(parsedData)
if let result = parsedData.result where parsedData.error == nil {

if let eventsData = result["events"] as? [[String : String]] {

for event in eventsData {

events.append(Event(eventData: event)) // Create an event from JSON data and add to the list
}
}

}
} catch {}
}
}

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

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! CustomCell

cell.name.text = events[indexPath.row].name
cell.detail.text = events[indexPath.row].details
cell.photo.image = events[indexPath.row].image

return cell
}

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

if segue.identifier == "detailsSegue" {
guard let eventVC = segue.destinationViewController as? DetailsViewController,
let eventIndex = tableView.indexPathForSelectedRow?.row else {
return
}
// set the event to detail view controller
eventVC.event = events[eventIndex]

}
}

// Standard JSON parsing code
func parseJSON(data: NSData) -> (result: [String : AnyObject]?, error: NSError?) {

var parsingError: NSError? = nil
let parsedResult: [String : AnyObject]?
do {

parsedResult = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments) as? [String : AnyObject]
} catch let error as NSError {

parsingError = error
parsedResult = nil
}
return (parsedResult, parsingError)
}
}

希望这有帮助!

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com