我试图将单元格的背景颜色设置为等于字典中的 UI 颜色,但我不断收到以下错误。即使将其作为数组传递时它也能工作吗?
import UIKit
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var tableView: UITableView!
let colourList = [["Color" : "Red", "colourCode" : UIColor.redColor()],
["Color" : "Yellow", "colourCode" : UIColor.yellowColor()],
["Color" : "Purple", "colourCode" : UIColor.purpleColor()],
["Color" : "Green", "colourCode" : UIColor.greenColor()],
["Color" : "Blue", "colourCode" : UIColor.blueColor()],
["Color" : "Orange", "colourCode" : UIColor.orangeColor()]]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.tableView.dataSource = self
self.tableView.delegate = self
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = UITableViewCell()
let dict = colourList[indexPath.row]
print(dict) // e.g ["Colour": "Red", "colourCode": UIDeviceRGBColorSpace 1 0 0 1]
print(dict["colourCode"]!) // e.g UIDeviceRGBColorSpace 1 0 0 1
cell.backgroundColor = dict["colourCode"] \\ ERROR - Cannot assign a value of type 'NSObject?' to a value of type 'UIColor?'
return cell
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.colourList.count
}
}
最佳答案
用作!明确告诉它的类型
cell.backgroundColor = dict["colourCode"] as! UIColor
关于ios - 无法将类型 'NSObject?' 的值分配给类型 'UIColor?' 的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32295491/