imageview没有相应更新

时间:2018-12-09 03:37:47

标签: ios swift xcode uiscrollview uiimageview

我想用从照片库中选择的照片创建一个图像视图,并通过按一个按钮显示在滚动视图中。但是图像在选择后不显示,仅在再次按下按钮时显示。有人可以帮我吗?

@IBAction func imageBtnPressed(_ sender: Any) {

    imagePicker()

    let imageView = UIImageView(frame: CGRect(x: (scrollView.bounds.size.width-200)/2, y:(scrollView.bounds.size.height-100)/2, width: 200, height: 100))
    imageView.image = imageOnCanvas
    imageView.contentMode = .scaleAspectFill
    imageView.clipsToBounds = true
    scrollView.addSubview(imageView)

}


func imagePicker(){
    let imagePicker = UIImagePickerController()
    imagePicker.delegate = self
    imagePicker.sourceType = .photoLibrary
    imagePicker.allowsEditing = false
    present(imagePicker, animated: true, completion: nil)
}


func imagePickerControllerDidCancel(_ picker: UIImagePickerController)
{
    dismiss(animated: true, completion: nil)
}


func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {

    let selectedImage = info[.originalImage] as? UIImage
    imageOnCanvas = selectedImage
    dismiss(animated: true, completion: nil)
}

1 个答案:

答案 0 :(得分:1)

您的代码不会仅因为呈现了UIImagePickerController而暂停。因此,让我们来看一下您的代码:

@IBAction func imageBtnPressed(_ sender: Any) {
    imagePicker()
    let imageView = UIImageView(frame: CGRect(x: (scrollView.bounds.size.width-200)/2, y:(scrollView.bounds.size.height-100)/2, width: 200, height: 100))
    imageView.image = imageOnCanvas
    imageView.contentMode = .scaleAspectFill
    imageView.clipsToBounds = true
    scrollView.addSubview(imageView)
}
func imagePicker(){
    let imagePicker = UIImagePickerController()
    imagePicker.delegate = self
    imagePicker.sourceType = .photoLibrary
    imagePicker.allowsEditing = false
    present(imagePicker, animated: true, completion: nil)
}

这恰好是 这样说(用imagePicker函数的内容代替函数调用):

@IBAction func imageBtnPressed(_ sender: Any) {
    let imagePicker = UIImagePickerController()
    imagePicker.delegate = self
    imagePicker.sourceType = .photoLibrary
    imagePicker.allowsEditing = false
    present(imagePicker, animated: true, completion: nil)
    let imageView = UIImageView(frame: CGRect(x: (scrollView.bounds.size.width-200)/2, y:(scrollView.bounds.size.height-100)/2, width: 200, height: 100))
    imageView.image = imageOnCanvas
    imageView.contentMode = .scaleAspectFill
    imageView.clipsToBounds = true
    scrollView.addSubview(imageView)
}

好了,正如您可以清楚地看到的那样,当您尚未设置imageOnCanvas时,就是在指它。 imagePicker仍在显示;用户尚未选择照片。但是您的代码已完全结束。您已经继续添加了一个子视图,该子视图由图像视图组成,该图像视图包含代码开始前imageOnCanvas 中的图像