自定义UITableView标头设置背景颜色失败

时间:2015-10-14 06:33:06

标签: ios swift uitableview

我创建了一个自定义的UITableViewHeaderFooterView,并且tableview的背景颜色为白色。

self.contentView.backgroundColor = UIColor.clearColor()

但是,标题标题的背景始终显示为灰色。如何删除灰色背景?

enter image description here

因为我已经覆盖了UITableView的drawRect函数,所以我希望在标题视图后面出现一些东西。

我尝试了以下内容:

a)将UITableView样式更改为Grouped,问题出在了,但标题不能粘在桌面上。

b)使用节标题标题而不是标题视图

func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String?

标题的背景是透明的,但我有多个标签。

任何人都可以帮我解决这个问题吗?

感谢@Omkar,设置了正确的方法

cell.layer.backgroundColor = UIColor.clearColor().CGColor

2 个答案:

答案 0 :(得分:3)

您需要设置内容视图的背景颜色以清除颜色,同时还需要设置tableView单元格的背景颜色以清除颜色。将其放在viewForHeaderInSection方法中。然后,您将能够看到设置为tableView的颜色。

    YourCell.contentView.backgroundColor = UIColor.clearColor()
    YourCell.backgroundColor = UIColor.clearColor()

请查看我的代码的附加图像以及故事板中样式简洁的表格视图。我还添加了运行后的外观图像

enter image description here

enter image description here

enter image description here

由于

答案 1 :(得分:0)

这是我的ViewController代码,唯一的区别是我使用headerfootview子类。我将tableview的背景设置为蓝色,如果我向下拉一点,你会看到在标题上看起来像一个掩码。

enter image description here

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

@IBOutlet weak var tableView: UITableView!


override func viewDidLoad() {
    super.viewDidLoad()
    tableView.dataSource = self
    tableView.delegate = self
    tableView.registerClass(UITableViewHeaderFooterView.self, forHeaderFooterViewReuseIdentifier: "HeaderCell")

    // 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.
}


func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return 4
}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 10
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("CustomCell", forIndexPath: indexPath)
    cell.textLabel?.text  = "\(indexPath.row)"
    return cell
}

func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let cell = tableView.dequeueReusableHeaderFooterViewWithIdentifier("HeaderCell") as UITableViewHeaderFooterView!

    cell!.textLabel?.text = "Header"
    cell!.contentView.backgroundColor = UIColor.clearColor()
    cell.backgroundColor = UIColor.clearColor()

    return cell
}

}

相关问题