当tableview改变时,单元格中的子视图会丢失颜色

时间:2014-11-01 13:45:31

标签: ios iphone uitableview swift custom-cell

我有一个UITableView,它有一个动态子视图。

当表是静态的时,它看起来像这样: enter image description here 带有T的圆形视图是自定义子视图

但是当我选择编辑并拖动表格单元格时,它会丢失它的颜色和T。

enter image description here

是什么原因?

我像这样初始化单元格(它是IB Cell的原型):

    func configureCell(cell: UITableViewCell, atIndexPath indexPath: NSIndexPath) {
        let object = self.fetchedResultsController.objectAtIndexPath(indexPath) as Item
        //cell.textLabel.text = object.valueForKey("name")!.description
        let cSubView = cell.viewWithTag(100) as RoundedIcon
        cSubView.setUpViewWithFirstLetter(String(first(object.name)!).uppercaseString)
    }

RoundedIcon的工作原理如下:

override init(frame: CGRect) {
    super.init(frame: frame)
    self.layer.cornerRadius = self.frame.size.width / 2;
    self.layer.borderWidth = 1.0;
    self.layer.borderColor = UIColor.lightGrayColor().CGColor;
    self.clipsToBounds = true;
}

func setUpViewWithFirstLetter(letter:String){
        self.backgroundColor = RoundedIcon.UIColorFromRGB(0x68C3A3)
        let theLetterLabel = UILabel()
        theLetterLabel.text = letter
        theLetterLabel.textColor = UIColor.whiteColor()
        theLetterLabel.textAlignment = .Center
        theLetterLabel.font = UIFont.systemFontOfSize(25)
        self.addSubview(theLetterLabel)
        theLetterLabel.frame = CGRect(origin: CGPoint(x: 0, y: 0), size: self.frame.size)
    }

1 个答案:

答案 0 :(得分:1)

@ rdelmar的评论向我指出了UITableview将其所有单元格的背景颜色更改为:

UIColor(white:0,alpha:0)

如果你不希望你的视图改变它的颜色,你应该更改backgroundColor属性setter,它可以像swift一样工作:

//override this setter to avoid color resetting on drag
override var backgroundColor:UIColor?{
    didSet {
        //check the color after setting - you also can do it earlier
        if let bgCol = backgroundColor{
            println(bgCol)
            if bgCol == UIColor(white: 0, alpha: 0){ //check if it's settled by the table
                super.backgroundColor = yourColor //set it back to your color
            }
        }
    }
}
相关问题