我有UITableView
,每个单元格包含UIImageView
和UIButton
。我点击按钮后启动相机,我正在尝试更新该单元格的索引路径中的UIImageView
。这是我到目前为止所尝试的,但图像没有更新:
import UIKit
class ViewController: UIViewController, UITableViewDelegate,
UITableViewDataSource, UIImagePickerControllerDelegate,
UINavigationControllerDelegate {
var objects = ["cup", "phone", "shoe", "tv"]
var images = [UIImage?](repeating:nil, count: 4)
var imageTaken : UIImage!
var imagePicker : UIImagePickerController?
@IBOutlet weak var tableView: UITableView!
@IBAction func TakePhoto(_ sender: UIButton) {
imagePicker!.sourceType = .camera
present(imagePicker!, animated: true, completion: nil)
images[sender.tag] = imageTaken
self.tableView.reloadData()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return objects.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = Bundle.main.loadNibNamed("CustomTableViewCell", owner: self, options: nil)?.first as! CustomTableViewCell
cell.buttonOutlet.tag = indexPath.row
cell.buttonOutlet.addTarget(self, action: #selector(ViewController.TakePhoto(_:)), for: .touchUpInside)
cell.imageFound.image = images[indexPath.row]
return cell
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
self.imageTaken = pickedImage
}
dismiss(animated: true, completion: nil)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
dismiss(animated: true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
imagePicker = UIImagePickerController()
imagePicker?.delegate = self
}
}
答案 0 :(得分:1)
不要将self.imageTaken
定义为UIImage
,而是在显示UIImagePickerController
时选择保留对indexPath.row的引用,然后在didFinishPickingMediaWithInfo
方法中传递图像中的图像根据{{1}}
类似
indexPath.row