菜鸟教程小白 发表于 2022-12-11 19:53:49

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


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

<p><strong>这里附上 JSON 响应:</strong> </p>

<pre><code>{
    &#34;Notification_Details&#34;:
    [
      {
            &#34;student_id&#34;: 2,
            &#34;date&#34;: &#34;2017-06-03T00:00:00&#34;,
            &#34;message&#34;: &#34;Notification Message 3&#34;
      },
      {
            &#34;student_id&#34;: 2,
            &#34;date&#34;: &#34;2017-06-02T00:00:00&#34;,
            &#34;message&#34;: &#34;Notification Message 2&#34;
      },
      {
            &#34;student_id&#34;: 2,
            &#34;date&#34;: &#34;2017-06-01T00:00:00&#34;,
            &#34;message&#34;: &#34;Notification Message 1&#34;
      }
    ]
}
</code></pre>

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

<pre><code>import UIKit

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

var notilabell : Array = ()
var datelabel : Array = ()


override func viewDidLoad() {
    super.viewDidLoad()

   self.getnotiJSON()

}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -&gt; Int {

    return notilabell.count

}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -&gt; UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: &#34;cell&#34;, for: indexPath) as! NotiCellTableViewCell

         cell.noti.text = notilabell
    cell.datenotification.text = datelabel



    return cell

}

func getnotiJSON()
{
      let url = NSURL(string: &#34;http://ezschoolportalapi.azurewebsites.net/api/Student/NotificationDetails?schoolid=1&amp;studentid=2&#34;)
    let request = NSMutableURLRequest(url: url! as URL)
    let task = URLSession.shared.dataTask(with: request as URLRequest) { (data, response, error)
      in
      guard error == nil &amp;&amp; data != nil else
      {
            print(&#34;Error:&#34;,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: &#34;Notification_Details&#34;) as? NSArray

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

                              let notiname = notidict?.value(forKey: &#34;message&#34;)

                                    self.notilabell.append(notiname as! String)

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

                        }

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

    }
    task.resume()
    }

}
</code></pre></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>错误在于您在解析日期时使用的日期格式化程序。此外,您所在日期的 key 也是错误的。尝试使用</p>

<pre><code>    let notidat = notidict?.value(forKey: &#34;date&#34;) as! String
    let dateformatter = DateFormatter()
    dateformatter.dateFormat = &#34;yyyy-MM-dd&#39;T&#39;hh:mm:ss&#34;
</code></pre>

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

<pre><code>let mynewdate = dateformatter.string(from: yourdate!)
self.notilabell.append(mynewdate as! String)
</code></pre>

<p><strong>收件人</strong></p>

<pre><code>let mynewdate = dateformatter.string(from: yourdate!)
self.datelabel.append(mynewdate as! String)
</code></pre></p>
                                   
                                                <p style="font-size: 20px;">关于ios - 使用swift 3将日期显示到tableview单元格时出现索引超出范围错误,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/44623199/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/44623199/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - 使用swift 3将日期显示到tableview单元格时出现索引超出范围错误