项目:https://github.com/vpags1/events.git
我需要将数据从TableView传递给ViewController。数据显示在具有两个标签和UIIMage(名称,详细信息,照片)的单元格上,单击该按钮会将您带到另一个显示信息的详细视图控制器。
我现在如何拥有它,数据存储在视图控制器中的三个数组中,但是当我与我的教授交谈时,他告诉我最简单的方法是将数据存储在一个单独的文件中。我真的不知道如何实现这一目标,无论是方式还是其他方法,我都会感激不尽。
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]
// }
//
// }
}
我的detailsViewController
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的设计者。感谢您的帮助!
答案 0 :(得分:0)
class CustomCell: UITableViewCell {
weak var superTableView: ViewController!
.....
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = self.eventsTable.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! CustomCell
cell.superTableView = self
}
现在您可以将数据传递给ViewController的任何属性
答案 1 :(得分:0)
您可以使用数组中的数据创建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"]!)
}
}
将一个Event类型的属性添加到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)
}
}
希望这有帮助!
答案 2 :(得分:0)
你的教授可能意味着将数据存储在另一个类/结构中,例如:
struct Data {
let name : String
let detail : String
let image : String
}
您可以使用此结构的数组来填充您的tableview:let data = [Data]
。
它非常直接,您可以像访问它一样访问它:
cell.name.text = data[indexPath.row].name
cell.detail.text = data[indexPath.row].detail
cell.photo.image = UIImage(named: data[indexPath.row].image)
通过使用数组(或字典/元组)数组也可以获得相同的结果:
let data = [["Brown Diner", "Free drink", "brown"], ["Kirkland", "Ladies drink", "kirk"]]
cell.name.text = data[indexPath.row][0]
cell.detail.text = data[indexPath.row][1]
cell.photo.image = UIImage(named: data[indexPath.row][2])
由于您已经开始使用prepareForSegue
,因此您可以使用以下内容传递数据:
在tableView(didSelectRowAtIndexPath:)
中使用以下内容启动segue并将数据作为发件人传递:
performSegueWithIdentifier("detailsSegue", sender: data[indexPath.row])
在prepareForSegue
:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "detailsSegue" {
let controller = segue.destinationViewController as! DetailsViewController
controller.info = sender as? Data // controller.info is an optional here
}
}
继续你已经拥有的东西,你可以像这样轻松地创建数组:
let names = ["Brown Diner", "Kirkland", "Choco"]
let details = ["Free drink", "Ladies free", "10% discount"]
let images = ["brown", "kirk", "choco"] // Changed this to an array of type String
let data = zip(zip(names, details), images).map { Data(name: $0.0.0, detail: $0.0.1, image: $0.1) }