ios - 如何根据在 Swift iOS 中单击的按钮更改 tableView numberOfRows 和 Cells
问题描述
我的用户个人资料页面中有两个按钮,一个用于保存的商店商品,一个用于他的评论。
我希望当用户单击保存的按钮时,它将在表格视图中加载他保存的商店的商品,当他单击评论按钮时,它将加载他的评论。
我正在努力弄清楚如何做到这一点
请问有什么帮助吗?
这是我的代码:
@IBOutlet weak var reviewsBtn: UIButton!
@IBOutlet weak var saveBtntab: UIButton!
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if(reviewsBtn.isSelected == true){
print("review selected")
return reviews.count
}
if(saveBtntab.isSelected == true){
print("saved selected")
return shops.count
}
return shops.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cellFave", for: indexPath) as! FaveTableViewCell
let shops = self.shops[indexPath.row]
let reviews = self.reviews[indexPath.row]
// i want to do the same idea for the number of rows here.
}
@IBAction func reviewsTapped(_ sender: Any) {
reviewsBtn.isSelected = true
reviewsBtn.isEnabled = true
faveBtntab.isEnabled = false
faveBtntab.isSelected = false
}
@IBAction func savedTapped(_ sender: Any) {
faveBtntab.isSelected = true
faveBtntab.isEnabled = true
reviewsBtn.isEnabled = false
reviewsBtn.isSelected = false
}
解决方案
首先,如果只有两种状态,您可以简化numberOfRows
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return reviewsBtn.isSelected ? reviews.count : shops.count
}
在cellForRow
做同样的事情时,显示项目取决于 reviewsBtn.isSelected
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cellFave", for: indexPath) as! FaveTableViewCell
if reviewsBtn.isSelected {
let reviews = self.reviews[indexPath.row]
// assign review values to the UI
} else {
let shops = self.shops[indexPath.row]
// assign shop values to the UI
}
}
并且不要忘记reloadData
在状态发生变化时调用。
推荐阅读
- node.js - 在 WebStorm 中调试 NPM 脚本?
- django - 为字节范围请求配置 Nginx 和 Django
- html - A website tells me my password is compromised, does this imply the website is also insecure?
- typescript - TypeScript:将结果转换为自定义类型不起作用
- python - 与 textarea 交互时出现 Selenium 错误
- java - openshift:jar maven 项目中没有主要清单属性
- python - os.tempnam() 在 c:/windows/temp 中创建临时文件失败
- git - 提交 a0946a562a8e 的樱桃采摘失败
- angular - 执行 Angular 代码时上传 Zip 文件错误
- javascript - 有没有办法隐藏页面的所有内容并仅在页面完全加载后显示它们?