查看UIImageView中的图像不是占位符图像,并附加到UIImage阵列
问题描述:
我为我的图像视图设置了一个占位符图像。用户可以将它们更改为来自其库的照片。一旦他们完成了这些,他们就可以将这些图像上传到数据库中。用户可以上传一个或多个图像,无论哪种方式,它们都以[UIImage]的形式上传。但是,我不希望占位符图像被上传。查看UIImageView中的图像不是占位符图像,并附加到UIImage阵列
我已经设法做到了这一点,但是以非常不正经的方式。我已经先继承的UIImageView做到了这一点,添加一个名为isSet属性和设置我的所有图像视图这个类:当图像之后用户设置
class ItemImageViewClass: UIImageView {
//keeps track of whether the image has changed from the placeholder image.
var isSet = Bool()
}
,然后选择了一个图像,isSet属性设置为true。
要检查是否在图像视图中的图像已经从占位符图像改变(即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
过滤器和地图不在占位符或无图像:
let imageArray = [imageViewOne, imageViewTwo, imageViewThree].filter
{ !$0.isPlaceholderImage() }.flatMap { $0.image }
print(imageArray) // imageViewThree.image
如果扩展名不适合您的要求的工作,我肯定会考虑“过滤器和flatMap“来避免if语句。
答
我会建议创建一个新的UI组件为您的需要与背景UIImageView(占位符)和一个可选的前景UIImageView(用户选择)。然后检查是否存在可选的前景UIImageView,因为您可以依赖这是包含用户选择的图像的UIImageView。
感谢您的回复,绝对比我的方法更好。我正在努力围绕代码的最后一部分将我的头包裹起来。我知道这个用例中的'.filter'会移除那些'.isPlaceholderImage'返回值为false的图像视图,但是'.flatMap {$ 0.image}'在这里做什么?我是否认为它正在访问元素的图像并将其添加到imageArray?我会认为'.map'会被用于那个? –
flatMap消除了阵列中的任何可选项 –