首页 > 解决方案 > UIView 作为 UITableView 的标头

问题描述

我正在通过《iOS 编程:大书呆子牧场指南(第 6 版)》一书快速学习 iOS 编程,但它似乎有点过时了。我在 Storyboard 中向 UIViewTable 添加标题时遇到了问题。在书中,它建议在原型单元格顶部添加一个 UIView,将带有约束的按钮放在那里,仅此而已,但就我而言,这不起作用。按钮不会显示 :( 所以,它看起来像这样: 在此处输入图像描述

你能帮我举个例子吗?

我的 ItemsViewController.swift:

import UIKit

class ItemsViewController: UITableViewController {

    var itemStore: ItemStore!

    @IBAction func addNewItem(_ sender: UIButton) {

    }

    @IBAction func toggleEditingMode(_ sender: UIButton) {

        if isEditing {
            sender.setTitle("Edit", for: .normal)
            setEditing(false, animated: true)
        } else {
            sender.setTitle("Done", for: .normal)
            setEditing(true, animated: true)
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "UITableViewCell")
    }

    override func numberOfSections(in tableView: UITableView) -> Int {

        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return itemStore.allItems.count + 1
    }

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

        let cell = tableView.dequeueReusableCell(withIdentifier: "UITableViewCell", for: indexPath)

        if itemStore.allItems.count == indexPath.row {

            cell.textLabel?.text = "No more items"
        } else {

            let item = itemStore.allItems[indexPath.row]
            cell.textLabel?.text = item.name
            cell.detailTextLabel?.text = "$\(item.valueInDollars)"
        }

        return cell
    }
}

UPD:我已经通过 以编程方式完成了该操作tableView(_:viewForHeaderInSection:),但这并不方便。有什么办法可以达到与故事板方式相同的效果吗?

标签: iosswiftuitableviewuiview

解决方案


我找到了万恶之源。如果您要像这样设置 ItemStore:

func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {

    guard let _ = (scene as? UIWindowScene) else { return }

    window = UIWindow(frame: UIScreen.main.bounds)
    window?.windowScene = (scene as! UIWindowScene)
    window?.rootViewController = ItemsViewController()
    window?.makeKeyAndVisible()

    // Create an ItemStore
    let itemStore = ItemStore()

    // Access the ItemsViewController and set its item store
    let itemsController = window!.rootViewController as! ItemsViewController
    itemsController.itemStore = itemStore
}

不要那样做。对我来说是这样的:

override func viewDidLoad() {
    super.viewDidLoad()

    itemStore = ItemStore()

    tableView.rowHeight = UITableView.automaticDimension
    tableView.estimatedRowHeight = 65
}

这本书似乎已经过时了。


推荐阅读