【问题标题】:Swift - set clear background color in UITableViewSwift - 在 UITableView 中设置清晰的背景颜色
【发布时间】:2019-11-26 16:00:06
【问题描述】:

我的UITableView 有问题。最终我希望它看起来像这样(白色矩形)。

如何设置.backgroundcolor 使其清晰,如图所示?? 我遇到的另一个问题是我的TableView 被“预填充”为空的cells..

我已经尝试过了,但不知何故它不起作用:

TableViewController

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: WhishCell.reuseID, for: indexPath)
    let currentWish = self.wishList[indexPath.row]
    cell.textLabel?.text = currentWish.wishName
    cell.backgroundColor = .clear
    return cell
}

自定义Cell

override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
    super.init(style: style, reuseIdentifier: reuseIdentifier)
    self.addSubview(checkButton)
    self.backgroundColor = .clear

}

我如何创建我的UITableView

let theTableView: WhishlistTableViewController = {
   let v = WhishlistTableViewController()
    v.view.layer.masksToBounds = true
    v.view.layer.borderColor = UIColor.white.cgColor
    v.view.backgroundColor = .clear
    v.view.layer.borderWidth = 2.0
    v.view.translatesAutoresizingMaskIntoConstraints = false
    return v
}()

我的UITableView 的所有功能都运行良好。只是backgroundcolor 和空的cells...

感谢您的帮助 :) 我在这方面找不到任何东西..

【问题讨论】:

    标签: ios swift uitableview tableview


    【解决方案1】:

    在您的WhishlistTableViewController 班级中:

    override func viewDidLoad() {
        super.viewDidLoad()
    
        // set background to clear
        tableView.backgroundColor = .clear
    
        // add clear view as tableFooterView
        // to prevent empty cells
        let v = UIView()
        v.backgroundColor = .clear
        tableView.tableFooterView = v
    
        // ... rest of table setup
        tableView.register(WishCell.self, forCellReuseIdentifier: "WishCell")
    }
    

    现在您的声明中不再需要 v.view.backgroundColor = .clear

    另一个选项,例如,如果您有时想要使用WhishlistTableViewController 的实例没有透明背景,请更改您的声明:

    let theTableView: WhishlistTableViewController = { ... }
    

    到:

    lazy var theTableView: WhishlistTableViewController = { ... }
    

    【讨论】:

    • lazy var 非常适合我,谢谢:) 你还知道如何使用 emtpy cells 禁用自动填充吗?我希望你知道我的意思:D
    • 您是否看到我的示例代码中添加明确的tableFooterView 以防止出现空行的注释?是这个意思吗?
    • 对不起,我实际上错过了:D,它再次完美运行.. 谢谢!非常感谢您的帮助
    猜你喜欢
    • 2014-09-04
    • 1970-01-01
    • 1970-01-01
    • 2021-10-26
    • 1970-01-01
    • 1970-01-01
    • 2017-02-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多