我有一个带有 2 个按钮的 tableview,一个按钮用于 today
,第二个按钮用于 yesterday
,如下所示以及以下数据,其中 tDays 的整数数组表示值像 Sunday = 1,....Saturday = 7
var tAnimals:[String] = ["Cat", "Dog", "Rabbit"]
var tDays:[[Int]] = [[3,4],[4,5],[5,6]]
class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {
@IBOutlet weak var myTableView: UITableView!
@IBOutlet weak var todayBtn: UIButton!
@IBOutlet weak var yesterdayBtn: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
}
func tableView(_ tableView:UITableView, numberOfRowsInSection section:Int) -> Int
{
return tAnimals.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let myCell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CustomCell
myCell.titleLabel.text = "Animals"
return myCell
}
}
现在,当我按下 todayBtn
时,我喜欢在表格 View 中看到 Dog and Rabbit
,因为今天是 Thursday = 5
,然后我按下yestredayBtn
,我喜欢看 猫狗
因为它是 星期三 = 4
。
我发现这个扩展是为了寻找工作日的值(value),但不知道如何将它应用为按钮标签
extension Date {
func dayNumberOfWeek() -> Int? {
return Calendar.current.dateComponents([.weekday], from: self).weekday
}
}
有没有一种方法可以将工作日的值分配为按钮标签,以便它们每天相应地自动更新并显示正确的数据。
最佳答案
可能是这样的,可能需要一些折射,我希望你能明白基本的想法:
class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {
var tAnimals:[String] = ["Cat", "Dog", "Rabbit"]
var tDays:[[Int]] = [[3,4],[4,5],[5,6]]
var arrdata:[String] = []
var today:Int!
var day:Int!
@IBOutlet weak var myTableView: UITableView!
@IBOutlet weak var todayBtn: UIButton!
@IBOutlet weak var yesterdayBtn: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
today = Date().dayNumberOfWeek()
}
//connect this IBAction with todayBtn & yesterdayBtn
@IBAction func actChangeData(_ sender: UIButton) {
arrdata.removeAll()
if sender == todayBtn {
day = today
} else {
day = today - 1
}
for i in 0...tAnimals.count-1 {
if tDays[i].contains(day) {
arrdata.append(tAnimals[i])
}
}
myTableView.reloadData()
}
func tableView(_ tableView:UITableView, numberOfRowsInSection section:Int) -> Int {
return arrdata.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let myCell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CustomCell
myCell.titleLabel.text = arrdata[indexPath.row]
return myCell
}
}
extension Date {
func dayNumberOfWeek() -> Int? {
return Calendar.current.dateComponents([.weekday], from: self).weekday
}
}
关于ios - 如何根据选择的日期显示 UITableView?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41373683/