ios - UITableView 单元格中的动态形状 (Swift)

标签 ios swift uitableview uiview

我是 Swift 的新手,很适合 UIView 类。我有一个带有 View 对象(左)和标签(右)的 TableView(下图)。表格本身工作正常,标签按预期显示。

TableView with custom cell

我遇到问题的地方是我希望标签旁边的 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,所以它会下降到默认情况。

如有任何建议,我们将不胜感激!!!!

最佳答案

当您设置 cellSymbol 时,您正在创建 Symbol 类的一个新实例。您永远不会修改 cellSymbol 的任何属性,因此它始终为黑色。

尝试:

cell.cellSymbol.inColor = self.tArray[2][indexPath.row]

关于ios - UITableView 单元格中的动态形状 (Swift),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35049672/

相关文章:

ios - 从书面数字中获取一个整数

ios - 在 Button Swift 中通过标签发送行和部分

ios - 我不断收到使用未解析的标识符错误

arrays - 如何在 Swift 中从数组设置多个 UILabel?

ios - 如何添加具有等于 uitableview 约束的 searchResultsTableView?

ios - 如何在 UITableView 之上显示 UIView?

ios - 在线/离线数据管理

ios - 如何在具有现有值的 uilabel 上添加一个值并显示它?

swift - 混合 Swift 和 Objective-C

ios - 由于 UITableviewCell 计数超过 10,如果我单击按钮顶部,它会自动单击最后一个 UITableViewCell 按钮。任何的想法?