这是我第一个使用 MVC 设计模式的程序,我不知道如何从模型获取值到我的 Controller 并在我的 View 中显示它。我会告诉你我做了什么。请澄清我做错了什么?或者告诉我如何以其他方式完成它。
型号
class songData: NSObject {
var artistName: String
var albumName: String
init(artistName: String, albumName: String) {
self.artistName = artistName
self.albumName = albumName
}
}
Controller
@IBAction func doTheSearch(sender: AnyObject) {
itunesAPI().itunesSearch({(song : songData) in
})
self.tableView.reloadData()
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return song1.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)
var artistAndAlbum = itunesAPI().array[indexPath.row]
cell.textLabel?.text =
cell.detailTextLabel?.text =
return cell
}
API
func itunesSearch(completionHandler:(songData)->()) {
Alamofire.request(.GET, "http://itunes.apple.com/search?", parameters: ["term" : "tamil new songs", "media" : "music"])
.responseJSON { (response) in
let json = JSON(response.result.value!)
if let jsonData = json["results"].arrayObject {
self.array = jsonData as! [[String : AnyObject]]
if self.array.count > 0 {
// self.array = jsonData as! [[String : AnyObject]]
// if let resultsDict = resultsArray.first {
let albumName = json["results"]["collectionName"].stringValue
let artistName = json["results"]["artistName"].stringValue
let song = songData(artistName: artistName, albumName: albumName)
completionHandler(song)
}
}
除了由带有单个单元格的 TableView 组成的 Storyboard外,我的 View 中什么也没有。我需要从 API 获取响应并将其显示在 View 中。
最佳答案
首先,您需要在返回数据后重新加载表格。将您的 IBAction 更新为:
itunesAPI().itunesSearch({(song : songData) in
self.tableView.reloadData()
})
否则 reloadData 将在返回数据之前被调用。在 viewController 上设置一个属性来存放数据。此外,最好以大写字母开头类名。
var tableData:[SongData] = [SongData]()
然后在数据成功返回时设置这个变量:
itunesAPI().itunesSearch({(song : songData) in
self.tableData.append(song) // add the result to the list of data
self.tableView.reloadData() // reload the table
})
然后这样设置单元格:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)
var artistAndAlbum = self.tableData[indexPath.row]
cell.textLabel?.text = artistAndAlbum.artistName
cell.detailTextLabel?.text = artistAndAlbum.albumName
return cell
}
关于swift - 如何从模型获取值到 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36649741/