将图像添加到单元格中

时间:2014-06-07 06:58:32

标签: uitableview swift xcode6

我已阅读大量问题,但似乎无法找到答案

我有一个TableView但无法将图像添加到我的手机

cell.imageView.image = UIImage(named: "osx_design_view_messages")

这段代码应该有用,因为我基本上是从问题的答案中复制了它,但由于某种原因它无效。有什么建议吗?

我顺便使用swift

 override func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell!
{
    let cellIdentifier = "cell"

    var cell : UITableViewCell

    cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as UITableViewCell
    cell.textLabel.text = self.recipies[indexPath.row]
    var image : UIImage = UIImage(named: "osx_design_view_messages")
    return cell
}

2 个答案:

答案 0 :(得分:36)

以下是导致问题的几个可能原因:

  1. 单元格原型需要包含UIImageView。如果您正在使用故事板,请选择单元格原型并确保其样式设置为" Basic"在属性检查器(右侧面板)中。

  2. 单元格标识符与故事板中原型单元格中键入的标识符不匹配。确保" cell"输入"标识符"也在属性检查器中。

  3. 图像未正确加载文件。要对此进行测试,请在初始化图像后添加以下行:

    println("The loaded image: \(image)")

  4. 检查故事板中是否已设置所有内容后,请尝试使用以下代码运行它:

    override func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell!
        {
            let cellIdentifier = "cell"
    
            var cell : UITableViewCell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as UITableViewCell
    
            cell.textLabel.text = self.recipes[indexPath.row]
    
            var image : UIImage = UIImage(named: "osx_design_view_messages")
            println("The loaded image: \(image)")
            cell.imageView.image = image
    
            return cell
        }
    

答案 1 :(得分:2)

Swift 3

//如果你的图像在服务器上,我们正在使用它。

//我们从网址获取图片。

//您可以从Xcode设置图像。

//正在使用为imageView分配标签

  1. 图片的网址是数组名称=缩略图,即self.thumbnail [indexPath.row]
  2. 在UITableviewCell上将imageView放在单元格
  3. 选择UIimageView从故事板中为其分配标签。

    let pictureURL = URL(string: self.thumbnail[indexPath.row])!
    let pictureData = NSData(contentsOf: pictureURL as URL)
    let catPicture = UIImage(data: pictureData as! Data)
    var imageV = UIImageView()
    imageV = cell?.viewWithTag(1) as! UIImageView
    imageV.image = catPicture
    
相关问题