我已经为我的 ImageView 设置了占位符图像。用户可以将它们更改为他们库中的照片。完成此操作后,他们可以将这些图像上传到数据库。用户可以上传单个图像或多个图像,无论哪种方式,它们都会作为 [UIImage] 上传。但是,我不希望上传占位符图像。
我已经成功实现了这一目标,但方式非常不优雅。我通过首先子类化 UIImageView、添加一个名为 isSet 的属性并将所有 ImageView 设置为此类来完成此操作:
class ItemImageViewClass: UIImageView {
//keeps track of whether the image has changed from the placeholder image.
var isSet = Bool()
}
然后,当用户选择图像后设置图像时,isSet 属性将设置为 true。
要检查 ImageView 中的图像是否已从占位符图像更改(即 isSet == true
),我使用了以下代码:
var imageArray: [UIImage]? = nil
if imageViewOne.isSet {
guard let mainImage = imageViewOne.image else {return}
if (imageArray?.append(mainImage)) == nil {
imageArray = [mainImage]
}
}
if imageViewTwo.isSet {
guard let imageTwo = imageViewTwo.image else {return}
if (imageArray?.append(imageTwo)) == nil {
imageArray = [imageTwo]
}
}
guard imageArray != nil else {
print("imageArray is nil")
alertMessage("Hey!", message: "Please add some images!")
return
}
当至少选择一张图像时,该数组将被保存到数据库中。
这看起来是一种非常困惑的方式;子类化 UIImageView 并必须使用一系列 if
语句检查每个图像是否已更改。有没有更优雅的方法来实现这一目标?谢谢
最佳答案
有一个解决方案,通过扩展UIImageView
来避免子类化。并且,使用 filter
和 flatMap
来绕过 if 语句。这要求您对每个 UIImageView
使用相同的占位符图像引用。
// In this example, the placeholder image is global but it doesn't have to be.
let placeHolderImage = UIImage()
extension UIImageView {
// Check to see if the image is the same as our placeholder
func isPlaceholderImage(_ placeHolderImage: UIImage = placeHolderImage) -> Bool {
return image == placeHolderImage
}
}
用法:
let imageViewOne = UIImageView(image: placeHolderImage)
imageViewOne.isPlaceholderImage() // true
let imageViewTwo = UIImageView()
imageViewTwo.isPlaceholderImage() // false
let imageViewThree = UIImageView()
imageViewThree.image = UIImage(named: "my-image")
imageViewThree.isPlaceholderImage() // false
过滤和映射非占位符或 nil 的图像:
let imageArray = [imageViewOne, imageViewTwo, imageViewThree].filter
{ !$0.isPlaceholderImage() }.flatMap { $0.image }
print(imageArray) // imageViewThree.image
如果扩展不能满足您的要求,我肯定会考虑“filter 和 flatMap”来避免 if 语句。
关于ios - 检查 UIImageView 中的图像不是占位符图像并附加到 UIImage 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46222209/