ios - 如何设置 UIImage 数组中的第二个或中间图像? ( swift 3)

标签 ios swift uiimage

我正在使用 imagePicker,它使我能够选择 4 个图像并创建所选图像的数组。我想用我选择的 4 个图像设置 4 个空 UIImageView 的图像。使用图像数组:images.first,我可以将第一个空 UIImageView 设置为我选择的第一张图像。我还可以使用 images.last 设置另一个空的 UIImageView 来获取第四个选定的图像。

如何将空 UIImageViews 的图像设置为我选择的第二个和第三个图像?

我正在使用“if let”检查数组的第一个和最后一个元素,但我不知道是否可以对第二个和第三个元素进行“if let”检查,以防止我的应用程序如果我不选择四个图像,则会崩溃。

    func doneButtonDidPress(_ imagePicker: ImagePickerController, images: [UIImage]) {

       let images = imageAssets

       if let imageOne = images.first {

        profileImageViewOne.image = imageOne

       }

       profileImageViewTwo.image = images[1]
       profileImageViewThree.image = images[2]

       if let imageFour = images.last {

        profileImageViewFour.image = imageFour

       }       


    }

最佳答案

您不需要使用 if let 语句,因为如果您使用索引从图像数组中获取图像,在这种情况下它们始终是非可选的。

为避免任何崩溃,您可以检查所选图像的数量。像这样的事情:

func doneButtonDidPress(_ imagePicker: ImagePickerController, images: [UIImage]) {

switch images.count {
    case 1:
    profileImageViewOne.image = images.first //you don't need to unwrap it, because imageView.image is an optional parameter
    case 2:
    profileImageViewOne.image = images.first
    profileImageViewTwo.image = images[1]
    case 3:
    profileImageViewOne.image = images.first
    profileImageViewTwo.image = images[1]
    profileImageViewThree.image = images.last
    case 4:
    //same way
    default: break
    }
}

还有另一种方法来填充 ImageView 。您也可以将 imageviews 的引用添加到数组中(例如在 viewDidLoad() 中)。

像这样

let views: [UIImageView] = [] //first we need to allocate an array
//then fill it inside viewDidLoad() or whatever
views = [profileImageViewOne, profileImageViewTwo, ...]

然后用它来设置图像:

    func doneButtonDidPress(_ imagePicker: ImagePickerController, images: [UIImage]) {

         //fill imageviews in order according to images count
         for (index, image) in images.enumerated() {
             let imageView = views[index]
             imageView.image = image
         }

         //if images count = 2, that method will fill only two imageviews with same indexes as images have. But it will not clear those views, that are out of range of images array
         //so if you need to clear them if images.count < views.count, you can use this:
         //put it before setting images to views, it will clear all imageviews
         views.forEach({$0.image == nil})


}

关于ios - 如何设置 UIImage 数组中的第二个或中间图像? ( swift 3),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45666275/

相关文章:

ios - 从 UITableView 的开关获取 indexPath

iOS 5.1 在使用 Collection View 时崩溃

swift - 在 Swift 中,你可以将一个字符串拆分为另一个字符串,而不仅仅是一个字符吗?

ios - 在 for 循环中将 PFFile 数组转换为 UIImage 返回空数组 Swift

objective-c - 尝试编码 UIImage 并存储到 NSUserdefault 时,应用程序变慢

iOS:获取图像的最大颜色

ios - UIButton touchDragInside 不起作用

ios - 无法设置 ImageView

ios - 在 Swift 4.1 中,你如何请求照片库的只写权限?

ios - UILabel 无法跟踪 AVAudioRecorder 当前录音时间