【发布时间】:2016-01-27 22:51:24
【问题描述】:
我是 Swift 的新手,很适合 UIView 类。我有一个带有视图对象(左)和标签(右)的 TableView(下)。表格本身工作正常,标签按预期显示。
我遇到的问题是我希望标签旁边的 View 对象包含各种形状和颜色,具体取决于支持表格的数组中的值...
var tArray = [["Row 1","Row 2", "Row 3", "Row 4", "Row 5"],
["Circle","Circle","Square","Square","Diamond"],
["Blue","Red","Green","Red","Purple"]]
所以在“第 1 行”旁边,我想要一个蓝色圆圈等。我已将 View 对象链接到自定义类。但我需要一种方法来动态创建形状并填充适当的颜色。
在 TableViewController 中,我有以下内容,它正在调用 Symbol 类,并且我正在返回一个黑色圆圈(我现在是硬编码的圆圈)...
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
cell.cellLabel.text = tArray[0][indexPath.row]
cell.cellSymbol = Symbol.init()
return cell
}
在我的自定义符号类中:
import UIKit
class Symbol: UIView {
var inColor: String
var inShape: String
init (in_color: String, in_shape: String) {
self.inColor = in_color
self.inShape = in_shape
super.init(frame: CGRect(x: 0, y: 0, width: 70, height: 70))
}
override func drawRect(rect: CGRect) {
let path = UIBezierPath(ovalInRect: rect)
switch self.inColor {
case "Green" : UIColor.greenColor().setFill()
case "Blue" : UIColor.blueColor().setFill()
case "Yellow" : UIColor.yellowColor().setFill()
case "Cyan" : UIColor.cyanColor().setFill()
case "Red" : UIColor.redColor().setFill()
case "Brown" : UIColor.brownColor().setFill()
case "Orange" : UIColor.orangeColor().setFill()
case "Purple" : UIColor.purpleColor().setFill()
case "Grey" : UIColor.darkGrayColor().setFill()
default: UIColor.blackColor().setFill()
}
path.fill()
}
required init?(coder aDecoder: NSCoder) {
self.inColor = ""
self.inShape = ""
super.init(coder: aDecoder)
}
override init(frame: CGRect) {
self.inColor = ""
self.inShape = ""
super.init(frame: frame)
}
}
我可能在这一切上都错了,我完全愿意接受其他方法。为了编译,我必须添加所需的 init?并覆盖 init(frame: CGRect) 整体。我还必须对 self.inColor 和 .inShape 进行初始化才能编译,但由于我没有将参数传递给它们,所以我没有什么可分配的。
所以我每次得到的都是一个黑色圆圈。我现在对圆圈进行硬编码以保持简单。开关 self.inColor 每次都是 nil,所以它会下降到默认情况。
任何建议将不胜感激!!!!
【问题讨论】:
-
到底是什么问题?
-
我想问题是 - 根据数组中的数据,在每个自定义表格单元格中获得适当颜色的形状的最佳方法是什么?我显然没有选择最好的方法,或者我没有正确执行。我已经放入了一些打印语句,似乎是“必需的初始化?”在我启动第一个符号之前就被调用了。我必须输入的各种 init 让我感到困惑。
标签: ios swift uitableview uiview