Swift:将图像设置为自定义单元格ImageView

时间:2017-01-24 13:53:46

标签: ios swift uitableview uiimageview

我想将图像设置为自定义单元格。我很困惑如何做到这一点。 假设我的UITable View中有一个自定义单元格。

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("CustomCellOne", forIndexPath: indexPath) as! CustomOneCell
    let tapGestureRecognizer = UITapGestureRecognizer(target:self, action:#selector(imageTapped(img:)))
    cell.imageView.isUserInteractionEnabled = true
    cell.imageView.addGestureRecognizer(tapGestureRecognizer)

    return cell
}

现在,只要点击图像,就会调用以下函数:

func imageTapped(img: AnyObject){
    print("Image clicked.")

    if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
        let imageData: NSData = UIImagePNGRepresentation(myImage)
        let image: UIImage = UIImage(data:imageData,scale:1.0)
        print(image)
        //i am uploading the photo from here. and i want to set this  picture to my cell imageView.
    }

    dismissViewControllerAnimated(true, completion: nil
}

我很困惑如何从这里调用单元格imageview? 我怎么能进一步采取?我只需要将获得的图像设置为单元格中的imgeView,其他一切正常。

1 个答案:

答案 0 :(得分:0)

这是我刚刚测试过的一个例子

我有一个名为ImageTableViewCell的自定义TableViewCell,它包含一个名为customImageView

的UIImageView
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
    let cell = tableView.dequeueReusableCell(withIdentifier: "cellImage", for: indexPath) as! ImageTableViewCell

    // initialising with some dummy data of mine
    cell.customImageView.image = UIImage(named: "Image\(indexPath.row).png")

    let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.imageTapped(_:)))
    cell.addGestureRecognizer(tapGesture)

    return cell
}

然后在ViewController

func imageTapped(_ sender: UITapGestureRecognizer)
{
    let myCell = sender.view as! ImageTableViewCell
    myCell.customImageView.image = UIImage(named: "imageTapped.jpg")
}

这应立即更新图像,无需重新加载表