【问题标题】:Can't change UITableView background color无法更改 UITableView 背景颜色
【发布时间】:2020-03-04 01:32:27
【问题描述】:

我有 UITableView,但无法更改它的背景,我尝试了很多但没有结果。

每次我尝试改变它的背景时都会在它后面翻转。所以,我尝试从 ViewController 实现 HomeView 但也没有任何改变。

包含 TableView 的 HomvView:

class HomeView: UIView {

    var recipes: Recipes?
    var recipesDetails = [Recipe]()
    let indicator = ActivityIndicator()

    let categories = ["italian food", "chinese food", "korean food", "italian food", "chinese food", "korean food", "italian food", "chinese food", "korean food", "italian food", "chinese food", "korean food"]

    override init( frame: CGRect) {
        super.init(frame: frame)
        layoutUI()
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    lazy var foodTableView: UITableView = {
        let foodTableView = UITableView()
        foodTableView.translatesAutoresizingMaskIntoConstraints = false

        foodTableView.delegate = self
        foodTableView.dataSource = self
        foodTableView.register(CategoriesTableViewCellCollectionViewCell.self, forCellReuseIdentifier: "CategoriesTableViewCellCollectionViewCell")
        foodTableView.register(HomeTableViewCell.self, forCellReuseIdentifier: "HomeTableViewCell")
        foodTableView.rowHeight = UITableView.automaticDimension
        foodTableView.showsVerticalScrollIndicator = false
        foodTableView.separatorStyle = .none
        return foodTableView
    }()

    func setupFoodTableView() {
        NSLayoutConstraint.activate([
            foodTableView.topAnchor.constraint(equalTo: topAnchor),
            foodTableView.bottomAnchor.constraint(equalTo: bottomAnchor),
            foodTableView.leadingAnchor.constraint(equalTo: leadingAnchor),
            foodTableView.trailingAnchor.constraint(equalTo: trailingAnchor)
        ])
    }

    func addSubview() {
        addSubview(foodTableView)
    }

    func layoutUI() {
        indicator.setupIndicatorView(self, containerColor: .customDarkGray(), indicatorColor: .white)
        addSubview()
        setupFoodTableView()
        fetchData()

    }

    func fetchData() {
        AF.request("https://apiurl.com").responseJSON { (response) in
            if let error = response.error {
                print(error)
            }
            do {
                if let data = response.data {
                    self.recipes = try JSONDecoder().decode(Recipes.self, from: data)
                    self.recipesDetails = self.recipes?.recipes ?? []
                    DispatchQueue.main.async {
                        self.foodTableView.reloadData()
                    }
                }

            } catch {
                print(error)
            }
            self.indicator.hideIndicatorView()
        }
    }

}

extension HomeView: UITableViewDelegate, UITableViewDataSource {

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return recipesDetails.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        if indexPath.row == 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "CategoriesTableViewCellCollectionViewCell", for: indexPath) as! CategoriesTableViewCellCollectionViewCell
            cell.collectionView.reloadData()
            return cell
        }

        let cell = tableView.dequeueReusableCell(withIdentifier: "HomeTableViewCell", for: indexPath) as! HomeTableViewCell
        let url = URL(string: recipesDetails[indexPath.row].image ?? "Error")
        cell.foodImage.kf.setImage(with: url)
        cell.foodTitle.text = recipesDetails[indexPath.row].title
        return cell

    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.row == 0 {
            return 160
        }
        return 350
    }

}

UITableViewCell:

class HomeTableViewCell: UITableViewCell {

    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        layoutUI()
        selectionStyle = .none

    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    lazy var containerView: UIView = {
        let containerView = UIView()
        containerView.backgroundColor = .white
        containerView.translatesAutoresizingMaskIntoConstraints = false
        containerView.layer.cornerRadius = 8.0
        return containerView
    }()

    lazy var foodImage: UIImageView = {
        let foodImage = UIImageView()
        foodImage.translatesAutoresizingMaskIntoConstraints = false
        foodImage.contentMode = .scaleAspectFill
        foodImage.clipsToBounds = true
        foodImage.layer.cornerRadius = 8.0
        return foodImage
    }()

    lazy var foodTitle: UILabel = {
        let foodTitle = UILabel()
        foodTitle.textColor = .CustomGreen()
        foodTitle.numberOfLines = 0
        foodTitle.translatesAutoresizingMaskIntoConstraints = false
        return foodTitle
    }()

    func setupContainerView() {
        NSLayoutConstraint.activate([
            containerView.topAnchor.constraint(equalTo: topAnchor, constant: 16),
            containerView.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -16),
            containerView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 16),
            containerView.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -16),
        ])
    }

    func setupFoodImage() {
        NSLayoutConstraint.activate([
            foodImage.topAnchor.constraint(equalTo: containerView.topAnchor),
            foodImage.leadingAnchor.constraint(equalTo: containerView.leadingAnchor),
            foodImage.trailingAnchor.constraint(equalTo: containerView.trailingAnchor),
            foodImage.heightAnchor.constraint(equalToConstant: 250)
        ])
    }

    func setupFoodTitle() {
        NSLayoutConstraint.activate([
            foodTitle.topAnchor.constraint(equalTo: foodImage.bottomAnchor, constant: 8),
            foodTitle.bottomAnchor.constraint(equalTo: containerView.bottomAnchor, constant: -8),
            foodTitle.leadingAnchor.constraint(equalTo: containerView.leadingAnchor, constant: 16),
            foodTitle.trailingAnchor.constraint(equalTo: containerView.trailingAnchor, constant: -16),

        ])
    }

    func addSubview() {
        addSubview(containerView)
        containerView.addSubview(foodImage)
        containerView.addSubview(foodTitle)
    }

    func layoutUI() {
        addSubview()
        setupContainerView()
        setupFoodImage()
        setupFoodTitle()
    }

}

请问我的代码有什么问题?

【问题讨论】:

  • tableView的颜色你改了哪一部分?
  • @Joshua 在 HomeView 中,foodTableView.backgroundColor = .gray 但什么也没发生

标签: ios swift uitableview


【解决方案1】:

我已经尝试了您的代码,只是将“foodTableView.backgroundColor = .gray”设置得很好。让我们在下面做一些事情并再次检查。

  1. layoutUI 添加self.backgroundColor = .red
  2. 初始时设置foodTableView.backgroundColor = .gray
  3. 运行应用程序并检查Debug View Hierarchy,您可以看到tableView 背景颜色为灰色。

我看到你在你的单元格上添加了containerView,所以如果我猜对了,你只想在周围显示containerView 和透明颜色。 所以让我们做一件小事。在HomeTableViewCelllayoutUI 上清除它的颜色self.backgroundColor = UIColor.clear 并再次检查。可能这是你的问题。

【讨论】:

  • 感谢您的帮助。我应该用清晰的颜色制作单元格,用白色制作容器,用我想要的颜色制作 UITableView。
【解决方案2】:

将tableview及其单元格的backgroundColor更改为您想要的样式。单元格显示的地方的颜色将是单元格的backgroundColor。另一个地方会显示tableview的backgroundColor。 如果一个tableveiw中有3个cell,tableview的backgroundColor为白色,cell的backgroundColor为橙色,cell区域的颜色为橙色,其他tableview区域的颜色为白色。

【讨论】:

  • 我不需要更改单元格的 backgroundColor 我需要它用于 TableView 我尝试但没有发生任何事情
  • @AhmedAbdElaziz 我没看到你的foodTableView.backgroundColor = UIColor.xxx。我的意思是,既然你想改变tableview的颜色,为什么不加这段代码呢?
  • @AhmedAbdElaziz 那么cell的数量呢?如果cell的数量很大,你可能没有机会看到tableview的颜色,因为cell只是覆盖了整个区域表视图。如果发生这种情况,那么你确实改变了tableview的颜色,你只是看不到它。
  • 我尝试更改TableView背景时有10个单元格,背景改变了但它变成了UITableView后面的UIView
  • @AhmedAbdElaziz 让我猜猜……你在单元格中制作了一个内部单元格,并试图让用户认为单元格的边缘是 tablview 的背景,对吧?
猜你喜欢
  • 1970-01-01
  • 2013-03-14
  • 2016-10-04
  • 2014-09-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多