我一直在阅读类似的问题,直到现在都没有解决这个错误或者我没有找到它。
我有一个 TableView,我需要该表具有特定的行数。
现在它可以处理来自数组的通知计数。在这个数组中,我保留了来自服务器的通知。 但我希望如果此数组计数大于 40,则行数为 40 而不是数组的计数。
这是我的代码:
class ClassName: UITableViewController, UITabBarControllerDelegate {
public var notifications: [APINotification] = []
override func viewDidLoad() {
super.viewDidLoad()
self.tabBarController?.delegate = self
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 140
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewDidAppear(_ animated: Bool) {
self.notifications = []
self.getLastNotifications()
APIAuth.shared.count_badge = 0
self.tabBarController?.tabBar.items![0].badgeValue = nil
}
public func getLastNotifications() {
let req = Notification()
req.getLastNotifications(onComplete: {events in
self.notifications = events
DispatchQueue.main.async(execute: {
self.tableView.reloadData()
})
})
}
override func numberOfSections(in tableView: UITableView) -> Int {
return self.notifications.count
}
// There is just one row in every section
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
// Set the spacing between sections
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 10
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let event = self.notifications[indexPath.section]
let cell = tableView.dequeueReusableCell(withIdentifier: "controller", for: indexPath) as! Controller
cell.bodyLbl.text = event.description
cell.typelbl.text = event.type
cell.typelbl.sizeToFit()
cell.titleLbl.text = event.title
cell.subjectLbl.text = event.subject?.name
return cell
} }
感谢您的帮助!
最佳答案
您可以将此方法更改为:
override func numberOfSections(in tableView: UITableView) -> Int {
return self.notifications.count > 40 ? 40 : self.notifications.count
}
这将显示您从通知中获得的行数,但如果它大于 40,它将只显示 40。要使其始终显示 40,只需输入 return 40,但这可能会使您的应用程序崩溃,因为数组将包含少于 40 个项目。
Ps 你显示 40 个部分没有行将它更改为行而不是你需要你的代码机会:
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.notifications.count > 40 ? 40 : self.notifications.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let event = self.notifications[indexPath.row]
...
}
关于ios - 如何构建具有特定行数的 TableView ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48206076/