• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

ios - 使用swift 3将日期显示到tableview单元格时出现索引超出范围错误

[复制链接]
菜鸟教程小白 发表于 2022-12-11 19:53:49 | 显示全部楼层 |阅读模式 打印 上一主题 下一主题

大家好,我的 tableview 中有一个自定义 UITableViewCell,有 2 个标签和一个 imageview。在第一个标签中,我正在获取通知消息数组,它将在 第二个标签中运行良好 m 在这种情况下获取日期数组 m 得到错误消息 Index out of Range。谁能帮助我如何解决它。在此先感谢

这里附上 JSON 响应:

{
    "Notification_Details":
    [
        {
            "student_id": 2,
            "date": "2017-06-03T00:00:00",
            "message": "Notification Message 3"
        },
        {
            "student_id": 2,
            "date": "2017-06-02T00:00:00",
            "message": "Notification Message 2"
        },
        {
            "student_id": 2,
            "date": "2017-06-01T00:00:00",
            "message": "Notification Message 1"
        }
    ]
}

下面是代码 m 用于获取 json 并加载到 tableview 单元格中。

import UIKit

class NotificationsViewController: UIViewController,UITableViewDataSource,UITableViewDelegate
{
@IBOutlet weak var mytable: UITableView!

var notilabell : Array = [String]()
var datelabel : Array = [String]()


override func viewDidLoad() {
    super.viewDidLoad()

   self.getnotiJSON()

}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return notilabell.count

}

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

    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! NotiCellTableViewCell

           cell.noti.text = notilabell[indexPath.row]
    cell.datenotification.text = datelabel[indexPath.row]



    return cell

}

func getnotiJSON()
{
        let url = NSURL(string: "http://ezschoolportalapi.azurewebsites.net/api/Student/NotificationDetails?schoolid=1&studentid=2")
    let request = NSMutableURLRequest(url: url! as URL)
    let task = URLSession.shared.dataTask(with: request as URLRequest) { (data, response, error)
        in
        guard error == nil && data != nil else
        {
            print("Error:",error)
            return
        }
        let httpstatus = response as? HTTPURLResponse
        if httpstatus?.statusCode == 200
        {
            if data?.count != 0
            {
            let responseString = try! JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary

                     let notiarray = responseString?.value(forKey: "Notification_Details") as? NSArray

                        for notifi in notiarray!
                        {
                            let notidict = notifi as? NSDictionary

                                let notiname = notidict?.value(forKey: "message")

                                    self.notilabell.append(notiname as! String)

                            let notidat = notidict?.value(forKey: "message") as! String
                            let dateformatter = DateFormatter()
                            dateformatter.dateFormat = "yyyy-MM-dd hh:mm:ss"
                           let mystring = dateformatter.string(from: Date())
                            let yourdate = dateformatter.date(from: mystring)
                            dateformatter.dateFormat = "dd-MM-yyyy"
                            let mynewdate = dateformatter.string(from: yourdate!)
                                    self.notilabell.append(mynewdate as! String)

                        }

                DispatchQueue.main.async                                 {
                    self.mytable.reloadData()
                    }
            }
            else
            {
                print("No data got from URL")
            }
        }
        else{
            print("error httpstatus code is :",httpstatus?.statusCode)
        }

    }
    task.resume()
    }

 }



Best Answer-推荐答案


错误在于您在解析日期时使用的日期格式化程序。此外,您所在日期的 key 也是错误的。尝试使用

    let notidat = notidict?.value(forKey: "date") as! String
    let dateformatter = DateFormatter()
    dateformatter.dateFormat = "yyyy-MM-dd'T'hh:mm:ss"

您将日期附加到 notilabell 数组而不是 datelabel 数组 更改以下代码

let mynewdate = dateformatter.string(from: yourdate!)
self.notilabell.append(mynewdate as! String)

收件人

let mynewdate = dateformatter.string(from: yourdate!)
self.datelabel.append(mynewdate as! String)

关于ios - 使用swift 3将日期显示到tableview单元格时出现索引超出范围错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44623199/

回复

使用道具 举报

懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关注0

粉丝2

帖子830918

发布主题
阅读排行 更多
广告位

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap