ios - 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:)
,但这并不方便。有什么办法可以达到与故事板方式相同的效果吗?
解决方案
我找到了万恶之源。如果您要像这样设置 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
}
这本书似乎已经过时了。
推荐阅读
- python - 当我使用 objecs.values('xx') 我失去了我的相关领域
- android - 对本地主服务器进行更改后,我们应该使用推送或合并到远程主服务器吗?
- powerbi - 当用户与用户表中的记录不匹配时,RLS 的行为如何?
- java - 根据 Servlet 规范,Servlet Request/InputStream 和 Response/OutputStream 的线程安全
- python - 使用 Python Regex 搜索文件并返回文件名
- python - TensorFlow - 交错多个独立预处理的 TFRecord 文件
- flutter - flutter_BottomNavigationBar_Context:找到了这个候选人,但参数不匹配
- c++ - 从非模板基类指针调用模板派生类方法的方法
- python - 在 unittest assert_call_with() 中引用嵌套函数
- python - 如何在python中将列传输到逗号分隔值文件中的行?