美文网首页
Swift 如何实现懒加载

Swift 如何实现懒加载

作者: jsone | 来源:发表于2020-02-27 15:06 被阅读0次

    通过懒加载来实现从相册或拍照添加图片
    1、声明懒加载属性imagePickerController

    lazy var imagePickerController: UIImagePickerController = {
        let vc = UIImagePickerController.init()
        vc.delegate = self
        vc.allowsEditing = true
        return vc
    }()
    

    2、显示相册和拍照选项的SheetView

    func showSheetView() -> Void {
        let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
        // 拍照选项
        let takingPicturesAction = UIAlertAction(title:"拍照", style: .default)
        {
            action in
            if UIImagePickerController.isSourceTypeAvailable(.camera) {
                self.imagePickerController.sourceType = .camera;
                self.present(self.imagePickerController, animated: true, completion: nil)
            } else {
                print("当前设备不支持拍照")
            }
        }
        // 相册选项
        let photoLibraryAction = UIAlertAction(title:"相册", style: .default)
        {
            action in
            self.imagePickerController.sourceType = .photoLibrary;
            self.present(self.imagePickerController, animated: true, completion: nil)
        }
        // 取消选项
        let cancelAction = UIAlertAction(title:"取消", style: .cancel, handler: nil)
        alertController.addAction(takingPicturesAction)
        alertController.addAction(photoLibraryAction)
        alertController.addAction(cancelAction)
        self.present(alertController, animated:true, completion:nil)
    }
    

    3、获取imagePickerController返回的图片

    // MARK: - UIImagePickerControllerDelegate, UINavigationControllerDelegate
    extension AddProductController : UIImagePickerControllerDelegate, UINavigationControllerDelegate {
        func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
            // 获取照片
            let image : UIImage = info[UIImagePickerController.InfoKey.editedImage] as! UIImage
            addPictureButton.setImage(image, for: .normal)
            addPictureButton.setTitle("", for: .normal)
            self.dismiss(animated: true, completion: nil)
        }
    }
    

    相关文章

      网友评论

          本文标题:Swift 如何实现懒加载

          本文链接:https://www.haomeiwen.com/subject/jvnthhtx.html