1 个 UIImagePickerController 和 2 个按钮

1 UIImagePickerController and 2 buttons

我有一个 UIImagePickerController 和 2 个按钮。当我点击按钮 1 时,我想设置按钮 1 的图像。当我点击按钮 2 时,我想设置按钮 2 的图像。我已经使用 UIImagePickerController 成功设置了按钮 1 的图像,但没有成功使用按钮 2。这是我的代码:

var whichButton: Int = 0

func displayImagePicker(){

    let imagePicker = UIImagePickerController()
    imagePicker.delegate = self
    imagePicker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
    imagePicker.allowsEditing = false

    self.presentViewController(imagePicker, animated: true, completion: nil)

}

@IBAction func chooseImageOne(sender: AnyObject) {

    displayImagePicker()

    whichButton = 1

}

@IBAction func chooseImageTwo(sender: AnyObject) {

    displayImagePicker()

    whichButton = 2

}

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

    self.dismissViewControllerAnimated(true, completion: nil)

    if whichButton == 1 {

        self.imageOne.setImage(image, forState: UIControlState.Normal)

    } else if whichButton == 2 {

        self.imageTwo.setImage(image, forState: UIControlState.Normal)

    }
}

如您所见,我尝试使用 var 来跟踪我正在点击的按钮。我不确定我在 didFinishPickingImage 函数中所做的是否正确。我是 swift 的新手,如果有人能提供一些帮助,那就太好了!提前致谢

您的代码在功能上是正确的。看起来你的 @IBAction 功能没有正确连接,或者第二个按钮的 @IBOutlet。您可以使用按钮处理程序或调试器中的打印语句轻松检查这一点。

我亲自检查了您在 xcode 上的代码,它是正确的。请查看您是否已将 IBOutlet 提供给 self.imageTwo 按钮,并检查 IBAction,即 imageTwo 按钮的 touchupInside。其他一切都很好