我有两个按钮button1
和button2
。点击这些按钮将显示UIImagePickerViewController
。在委托方法didFinishPickingMediaWithInfo
中,如何确定UIImagePickerViewController
所呈现的按钮的行为?
答案 0 :(得分:2)
您可以使用 Tag
属性识别您的对象,最初为每个UIButton指定标记,只要存在UIImagePickerController
,就会将按钮标记分配给 UIImagePickerController .view.tag ,例如
例如
@IBAction func buttonOneClick(_ sender:UIButton) {
//... code for present the UIImagePickerController
yourimagePicker.view.tag = sender.tag
}
@IBAction func buttonTwoClick(_ sender:UIButton) {
//... code for present the UIImagePickerController
yourimagePicker.view.tag = sender.tag
}
或者为您的UIButton创建常用方法
@IBAction func buttonPresentImage(_ sender:UIButton) {
//... code for present the UIImagePickerController
yourimagePicker.view.tag = sender.tag
}
最后你可以识别UIImagePickerController委托方法
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if picker.view.tag == button1.tag {
// its button1
} else {
// its button2
}
}
答案 1 :(得分:0)
取一个变量。
var selectedButtonTag: Int = 0
OnClick of按钮设置变量,如下所示。
@IBAction func buttonFirstClick(_ sender:UIButton) {
selectedButtonTag = 0
}
@IBAction func buttonSecondClick(_ sender:UIButton) {
selectedButtonTag = 1
}
在didFinishPickingMediaWithInfo方法中你可以这样做。
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if selectedButtonTag == 0 {
print("First button clicked.")
} else {
print("Second button clicked.")
}
}
答案 2 :(得分:0)
不要使用任何全局变量来执行此操作,您必须使用运行时例程objc_setAssociatedObject
和objc_getAssociatedObject
:
var kAssociatedObject = "associatedObject"
@IBAction func firstButtonAction(_ sender:UIButton) {
objc_setAssociatedObject(picker, &kAssociatedObject, sender, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
@IBAction func secondButtonAction(_ sender:UIButton) {
objc_setAssociatedObject(picker, &kAssociatedObject, sender, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String: Any]) {
let sender = objc_getAssociatedObject(picker, &kAssociatedObject)
if sender == firstButton {
//First button selected
} else if sender == secondButton {
//second button selected
}
//Now you have button object in your delegate method, you can check which button is selected and you also can associate any type of object and get data. This is the best way to attach and get the data from any object
}
你也可以使用这样的标签属性:
//set tag
var imagePicker = UIImagePickerController()
imagePicker.view.tag
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String: Any]) {
// get tag
let tagData = picker.view.tag
// you can handle your condition accordingly
}