【发布时间】:2015-01-15 10:32:24
【问题描述】:
我是 swift 编程的初学者,也是 ios 的新手。我正在尝试制作表格视图,但 if(cell == nil) 的条件但单元格从不为零并且不会进入条件这是我的代码。
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
//cell content declaration
var rightlabel = UILabel(frame: CGRectMake(200, 10, 200, 21))
var mainTextLabel = UILabel(frame: CGRectMake(10, 10, 200, 21))
var imageView = UIImageView()
var cell : UITableViewCell!
cell = tableView.dequeueReusableCellWithIdentifier("detailsCell") as? UITableViewCell
//cell content declaration END
if(cell == nil)
{
cell = tableView.dequeueReusableCellWithIdentifier("detailsCell", forIndexPath: indexPath) as UITableViewCell
let test: AnyObject? = myData?.objectForKey("\(indexPath.row + 1)")
let hrvalue : AnyObject? = test?.objectForKey("name")
let subtitle : NSNumber? = test?.objectForKey("distance") as? NSNumber
let icon : String = test?.objectForKey("icon") as String
//CUSTOM LABEL START FROM HERE
mainTextLabel.text = hrvalue as? String
rightlabel.text = "\(subtitle as Float ) k.m. away from here."
mainTextLabel.font = UIFont.systemFontOfSize(18.0)
rightlabel.font = UIFont.systemFontOfSize(14.0)
let image = UIImage(named: icon)
imageView = UIImageView(image: image!)
imageView.frame = CGRect(x: 120, y: 10, width: 30, height: 30)
mainTextLabel.tag = 4
rightlabel.tag = 50
imageView.tag = 100
cell.contentView.addSubview(mainTextLabel)
cell.contentView.addSubview(rightlabel)
cell.contentView.addSubview(imageView)
//CUSTOM LABEL END
}
if(cell != nil)
{
println("outside")
//FATCHING TAG & RETURN CELL
mainTextLabel = cell.viewWithTag(4) as UILabel
rightlabel = cell.viewWithTag(50) as UILabel
imageView = cell.viewWithTag(100) as UIImageView
}
return cell
// FATCHING TAG & RETURN CELL END
}
【问题讨论】:
-
您是在情节提要中使用原型单元格还是以其他方式针对重用标识符注册了类/笔尖?如果是这样,那么
dequeueReusableCellWithIdentifier将永远不会返回 nil。您在if cell==nil中的代码也没有意义 - 在未注册单元类或 nib 的传统方法中,在这种情况下您不调用dequeueReusableCellWithIdentifer:indexPath:,您实际上需要分配一个新单元跨度> -
是的,我在故事板中使用原型单元
-
我更改我的代码并将 cell = tableView.dequeueReusableCellWithIdentifier("detailsCell") 删除为? UITableViewCell 并将其添加到 if 单元格 != nil ,现在我得到 nil 值,但它没有进入 if 条件
-
不,如果您使用原型单元格,您只需调用
dequeueReusableCellWithIdentifier:并且您永远不会得到 nil - 所以所有添加文本字段等都应该通过原型单元格中的 Interface Builder 完成。
标签: ios uitableview swift