我正在使用AppCoda的Beginning Swift Programming一书,我似乎无法弄清楚这段代码有什么问题。
IO
此行抛出' AnyObject无法转换为' UITableViewCell'
import UIKit
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
var restaurantNames = ["Cafe Deadend", "Homei", "Teakha", "CafeLoisl", "Petite Oyster", "For Kee Restaurant", "Po's Atelier", "Bourke Street Bakery", "Haigh’s Chocolate", "Palomino Espresso", "Upstate", "Traif", "Graham Avenue Meats And Deli", "Waffle & Wolf", "Five Leaves", "Cafe Lore", "Confessional", "Barrafina", "Donostia", "Royal Oak", "CASK Pub and Kitchen"]
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// Return the number of rows in the section.
return restaurantNames.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) ->
UITableViewCell {
let cellIdentifier = "Cell"
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as UITableViewCell
// Configure the cell...
cell.textLabel.text = restaurantNames[indexPath.row]
return cell
}
}
我对Swift和iOS编程一般都很陌生,所以任何帮助都会受到赞赏。
答案 0 :(得分:3)
您需要将as
更改为as!
var cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell
还要确保已使用可重复使用的字符串名称"Cell"
答案 1 :(得分:2)
//MARK: Tableview
func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int
{
return tabledata.count
}
func tableView(tableView: UITableView!,
cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell!
{
let cell:UITableViewCell = UITableViewCell(style:UITableViewCellStyle.Default, reuseIdentifier:"Cell")
cell.textLabel?.text = tabledata[indexPath.row]
return cell
}
我已将此代码用于tableview ....您可以根据需要更改此内容。即使我是swift中的新手,否则我会更正您的代码。