加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

uitableview – Swift – 什么是向下转型?为什么我需要在tablev

发布时间:2020-12-14 04:50:04 所属栏目:百科 来源:网络整理
导读:下面的代码是在UItableview中显示单元格的名称. override func tableView(tableView: UITableView,cellForRowAtIndexPath indexPath: NSIndexPath) - UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell") as UITableViewCell
下面的代码是在UItableview中显示单元格的名称.

override func tableView(tableView: UITableView,cellForRowAtIndexPath
        indexPath: NSIndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCellWithIdentifier("Cell")
            as UITableViewCell

        cell.textLabel!.text = "Spring (indexPath.row + 1)"

        return cell
}

有一个编译错误,Xcode建议我将’as’更改为’as!’ –

let cell = tableView.dequeueReusableCellWithIdentifier("Cell")
        as! UITableViewCell

可能有人解释了什么是垂头丧气,为什么我们需要在这种情况下垂头丧气?

解决方法

OK ..lets让它变得非常简单.

在线上:

let cell = tableView.dequeueReusableCellWithIdentifier("Cell")

您正在访问tableView的方法dequeueReusableCellWithIdentifier,如果您查看文档,您可以看到返回类型是AnyObject?.

现在假设您要访问textLabel属性

cell.textLabel!.text = "Spring (indexPath.row + 1)"

你不能这样做.因为AnyObject上没有任何textlabel类型.

因此,您正在向下转发强制编译器更具体的类UITableViewCell,如下所示,因为稍后您尝试访问文本标签属性:

let cell = tableView.dequeueReusableCellWithIdentifier("Cell") as! UITableViewCell

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读