如何访问 UIImageView 以使用 Picker Controller 设置图像

How to access UIImageView to set image using Picker Controller

我正在以编程方式向 UITableViewCell 内的 UIImageView 添加一个按钮。但是,如何访问原始 imageView 以便将所选图像设置为 UIImageView?

我的代码:

  func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = theTableView.dequeueReusableCellWithIdentifier("SampleCell") as! UITableViewCell

     if indexPath.section == 2 {
        let imageView = UIImageView(frame: CGRectMake(0, 0, 320, 175))
        let button = UIButton(frame: CGRectMake(110, 30, 100, 100))
        let myImage = UIImage(named: "Camera-50.png")

        let touch = UITapGestureRecognizer()
        imageView.addGestureRecognizer(touch)
        imageView.layer.borderWidth = 0.5

        button.setImage(myImage, forState: UIControlState.Normal)
        button.addTarget(self, action: "getImage", forControlEvents: .TouchUpInside)
        cell.addSubview(button)
        cell.addSubview(imageView)
    }

    return cell
}



func getImage() {


    let picker = UIImagePickerController()
    picker.allowsEditing = true
    picker.delegate = self

    presentViewController(picker, animated: true, completion: nil)
}

func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage!, editingInfo: [NSObject : AnyObject]!) {

    //need to access imageView to set image

}

尽管从技术上讲,您可以通过将 UIImagePickerControllerDelegate 方法存储在 class 变量中来访问 UIImageView,但您应该将 UIImageView 的图像设置为您的 cellForRowAtIndexPath: 方法使用从图像选择器返回的图像,例如:

var image:UIImage?

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = theTableView.dequeueReusableCellWithIdentifier("SampleCell") as! UITableViewCell

     if indexPath.section == 2 {
        let imageView = UIImageView(frame: CGRectMake(0, 0, 320, 175))
        if let image = image {
            imageView.image = image
        }

        let button = UIButton(frame: CGRectMake(110, 30, 100, 100))
        let myImage = UIImage(named: "Camera-50.png")

        let touch = UITapGestureRecognizer()
        imageView.addGestureRecognizer(touch)
        imageView.layer.borderWidth = 0.5

        button.setImage(myImage, forState: UIControlState.Normal)
        button.addTarget(self, action: "getImage", forControlEvents: .TouchUpInside)
        cell.addSubview(button)
        cell.addSubview(imageView)
    }

    return cell
}

func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) {

    dismissViewControllerAnimated(true, completion: nil)
    image = info[UIImagePickerControllerOriginalImage] as? UIImage
    yourTableView.reloadData()
}

注意:didFinishPickingImage: 自 iOS 3.0 以来已被弃用,因此我使用 imagePickerController:didFinishPickingMediaWithInfo: 代替它。