我有一个正方形,包含四个不同的图像,从图像库中加载后将显示两个图像,顶部两个,底部两个。
每个图像视图都与其个人按钮相关联,它将使用与用户库中相同的方法来拾取图像。
如何以相同的方法使用四个不同的按钮来显示在正确位置加载的图像?
我可以制作一个模型来执行此行为吗?
谢谢
@IBOutlet weak var topLeftImage: UIImageView!
@IBOutlet weak var topRightImage: UIImageView!
@IBOutlet weak var bottomLeftImage: UIImageView!
@IBOutlet weak var bottomRightImage: UIImageView!
@IBOutlet weak var topLeftButton: UIButton!
@IBOutlet weak var topRightButtom: UIButton!
@IBOutlet weak var bottomLeftButton: UIButton!
@IBOutlet weak var bottomRightButton: UIButton!
@IBAction func loadTopLeftImage(_ sender: Any) {
loadPhotoLibrary()
}
@IBAction func loadTopRightImage(_ sender: Any) {
loadPhotoLibrary()
}
@IBAction func loadBottomLeftImage(_ sender: Any) {
loadPhotoLibrary()
}
@IBAction func loadBottomRightImage(_ sender: Any) {
loadPhotoLibrary()
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
if let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
topLeftImage.image = image
}
self.dismiss(animated: true, completion: nil)
}
func loadPhotoLibrary() {
imagePicker.delegate = self
imagePicker.sourceType = UIImagePickerController.SourceType.photoLibrary
imagePicker.allowsEditing = false
self.present(imagePicker, animated: true)
}
答案 0 :(得分:0)
首先创建UIImagePickerController
的子类,并使用类型为completionHandler
的参数添加变量UIImage?
class YourPicker: UIImagePickerController {
var completionHandler: ((UIImage?) -> ())?
}
然后将参数添加到您的loadPhotoLibrary
函数中,该参数表示UIImageView
您要更改其image
。还要设置其完成处理程序:您想要更改某些ImageView的image
func loadPhotoLibrary(setImageView imageView: UIImageView) {
let imagePicker = YourPicker() // don't forget to initialize subclass
imagePicker.delegate = self
imagePicker.sourceType = UIImagePickerController.SourceType.photoLibrary
imagePicker.allowsEditing = false
imagePicker.completionHandler = { image in
if let image = image { // if you just dismiss picker, you don't want to delete previous image
imageView.image = image
}
}
self.present(imagePicker, animated: true)
}
现在在选择器的委托方法中将picker
下放为YourPicker
,并使用将键UIImagePickerController.InfoKey
的值强制转换为UIImage?
的调用完成(如果其值为nil
,没关系,只是没有设置ImageView的image
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
if let myPicker = picker as! YourPicker {
myPicker.completionHandler!(info[UIImagePickerController.InfoKey.originalImage] as? UIImage)
}
self.dismiss(animated: true, completion: nil)
}
然后在按钮操作中像这样调用您的loadPhotoLibrary
方法
@IBAction func loadTopLeftImage(_ sender: Any) {
loadPhotoLibrary(setImageView: topLeftImage)
}
...
答案 1 :(得分:0)
1- 如果您使用情节提要,请控制所有按钮并将其拖至相同方法。 如果您为每个按钮添加一个目标,请对同一方法显示所有选择器。
2-添加标签: 在情节提要中->您的按钮->给每个按钮一个唯一的标签 在代码中添加button.tag = uniqueTag
3- 在通用方法中,您可以为每个按钮使用一个开关(sender.tag)