gpt4 book ai didi

swift - TableView 类别细化

转载 作者:行者123 更新时间:2023-11-28 08:01:29 25 4
gpt4 key购买 nike

我在 tableview 上显示的 firebase 中有大量数据。数据是附近不同企业的数据,我想添加一个功能来按业务类型(食品、旅游、购物等)过滤/排序数据。我添加了一个带有分段控件的选项卡栏作为过滤/排序功能。当用户选择购物时,我只想显示购属性(property)务,删除所有其他业务。我尝试了几种不同的方法来做到这一点,但没有成功。 I am able to populate the tableview cells correctly when the app first loads but I cannot correctly load the cells when a filter/sort option is selected.这是我当前的代码。

@IBOutlet weak var selects: UISegmentedControl!
@IBAction func selections(_ sender: Any) {
if selects.selectedSegmentIndex == 0 {
//all
print("all")
cate = 0
loadposts()
}
else if selects.selectedSegmentIndex == 1 {
//shopping
print("shopping")
cate = 1
loadposts()
}
else if selects.selectedSegmentIndex == 2 {
//food
print("food")
cate = 2
loadposts()
}
else if selects.selectedSegmentIndex == 3 {
//travel
print("travel")
cate = 3
loadposts()
}
else if selects.selectedSegmentIndex == 4 {
//events
print("event")
cate = 4
loadposts()
}
else {
//more
print("more")
cate = 5
loadposts()
}
}

func loadposts() {
ref = Database.database().reference()
let trace = Performance.startTrace(name: "test trace")
trace?.incrementCounter(named:"retry")
let userID = Auth.auth().currentUser?.uid
print(userID!)


ref.child("Users").child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in
// Get user value
let value = snapshot.value as? NSDictionary
let one1 = value?["Coupon Book"] as? String ?? ""
let two2 = value?["charitylogo"] as? String ?? ""
print("one1: \(one1)")
bogus.set(one1, forKey: "bogus")
let url = URL(string: two2)
print("Url: \(url!)")
URLSession.shared.dataTask(with: url!, completionHandler: { (data, response, error) in
if error != nil{
print(error)
return
}
DispatchQueue.main.async {
/// self.centernavlogo = UIButton(type: .custom)
let pim = UIImage(data: data!)
self.vood.background = pim
///self.centernavlogo.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
/// self.centernavlogo.imageView?.contentMode = .scaleAspectFit
/// self.centernavlogo.setImage(pim, for: .normal)
/// self.centernavlogo.setBackgroundImage(pim, for: .normal)

/// self.centernavlogo.tintColor = UIColor.white

///self.centernavlogo.setBackgroundImage(pim, for: .normal)


}

}).resume()

Database.database().reference().child("Coupons").child(one1).observe(.childAdded) { (Snapshot : DataSnapshot) in
if let dict = Snapshot.value as? [String: Any] {
let captiontext = dict["company name"] as! String
let offerx = dict["totaloffer"] as! String
let logocomp = dict["logo"] as! String
let actchild = dict["childx"] as! String
let categ = dict["category"] as! String
let post = Post(captiontext: captiontext, PhotUrlString: actchild, offertext: offerx, actualphoto: logocomp, cat2: categ)
self.posts.append(post)
self.tableview.reloadData()

print(self.posts)
}
}
}) { (error) in
print(error.localizedDescription)
}
trace?.stop()
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.

}
func delay(_ delay:Double, closure:@escaping ()->()) {
let when = DispatchTime.now() + delay
DispatchQueue.main.asyncAfter(deadline: when, execute: closure)
}

}
extension ViewController : UITableViewDataSource {


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

let cell = tableview.dequeueReusableCell(withIdentifier: "PostCell", for: indexPath) as! prot

if cate == 0{
///home
if posts[indexPath.row].cat1 == "" {

}else{

}
}else
if cate == 1{
///shopping
if posts[indexPath.row].cat1 == "shopping" {

}
}else
if cate == 2{
///food
if posts[indexPath.row].cat1 == "food" {

}
}else
if cate == 3{
///travel
if posts[indexPath.row].cat1 == "travel" {

}
}else
if cate == 4{
///event
if posts[indexPath.row].cat1 == "event" {

}
}else
if cate == 5{
///more
if posts[indexPath.row].cat1 == "more" {
posts.remove(at: indexPath.item)

DispatchQueue.main.async {
tableView.deleteRows(at: [indexPath], with: UITableViewRowAnimation.none)
}
print("category 5 running")
}
tableView.reloadData()
}
if cate == 6{
///gps
}

cell.cllimg?.image = nil
cell.maintxt.text = nil
cell.sidetxt.text = nil
cell.maintxt.text = posts[indexPath.row].caption
cell.sidetxt.text = "Offers: \(posts[indexPath.row].offercount)"



let hone = posts[indexPath.row]
if let maria = hone.actphot {
let url = URL(string: maria)
URLSession.shared.dataTask(with: url!, completionHandler: { (data, response, error) in
if error != nil{
print(error)
return
}
cell.cllimg?.contentMode = .scaleAspectFit
DispatchQueue.main.async {

cell.cllimg?.image = UIImage(data: data!)
}

}).resume()
}

return cell
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return posts.count
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

passinfo.set("\(posts[indexPath.row].photourl)", forKey: "passinfo")
self.performSegue(withIdentifier: "yourSegue", sender: self)
}



}

使用上面的代码,选择类别时表格为空白

if cate == 5{
///more
if posts[indexPath.row].cat1 == "more" {
tableView.beginUpdates()
posts.remove(at: indexPath.item)
tableView.deleteRows(at: [indexPath], with: UITableViewRowAnimation.none)
print("category 5 running")
}
tableView.endUpdates()
}

使用上面的代码,应用程序崩溃并给我这个错误。

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of rows in section 0. The number of rows contained in an existing section after the update (14) must be equal to the number of rows contained in that section before the update (15), plus or minus the number of rows inserted or deleted from that section (0 inserted, 0 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out).'

我也尝试删除 posts.remove(at: indexPath.item)tableView.deleteRows(at: [indexPath], with: UITableViewRowAnimation.none) 但是都没有用。

最佳答案

尝试在 tableView.beginUpdates() 之前移动这一行

posts.remove(at: indexPath.item)

The number of rows contained in an existing section after the update (14) must be equal to the number of rows contained in that section before the update (15), plus or minus the number of rows inserted or deleted from that section (0 inserted, 0 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out).

因为错误表明更新前的帖子数组计数在更新后也必须相等。

posts.remove(at: indexPath.item)
tableView.beginUpdates()
tableView.deleteRows(at: [indexPath], with: UITableViewRowAnimation.none)
tableView.endUpdates()

关于swift - TableView 类别细化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46566529/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com