2017-05-23 3 views
0

사용자 정의 하위 뷰에서 UIImagePickerController의 인스턴스를로드하려고합니다. 몇 가지 이유 때문에 일을하고 나에게주는 유지하지 않습니다 여기에하위 뷰에서 UIImagePickerController로드 중

<UIImagePickerController: 0x7fde7282bc00> on <UIViewController: 0x7fde6f507f00> whose view is not in the window hierarchy! 

의 내 코드가 어떻게 생겼는지의 골격 :

보기 컨트롤러

let subview = SubView() 
// Subview params... 
subview.parent = self 
self.view.addSubview(subview) 

서브 뷰

class SubView: UIView, UIImagePickerControllerDelegate, UINavigationControllerDelegate { 

    let imagePicker = UIImagePickerController() 

    var parent = UIViewController() 

    override func draw(_ rect: CGRect) { 
     imagePicker.delegate = self 
     let add = UIButton() 
     // add params... 
     add.addTarget(self, action: #selector(addImg(_:)), for: .touchUpInside) 
     self.addSubview(add) 
    } 

    func addImg(_ sender: UIButton) { 

     imagePicker.allowsEditing = false 
     imagePicker.sourceType = .photoLibrary 

     parent.present(imagePicker, animated: true, completion: nil) 

    } 

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { 

     if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage { 
      // Do stuff with image 

     } 

    } 

} 

내가 어떻게이 일을 얻을 수있는 아이디어?

답변

0

현재 rootControllerUIApplication을 사용하여 확인할 수 있습니다. 이것은 제 작업 코드입니다. 이

if let rootController = UIApplication.shared.keyWindow?.rootViewController { 

    if rootController is UINavigationController { 
     if let navigationController = rootController as? UINavigationController { 
      if let topViewController = navigationController.topViewController { 
       topViewController.present(alert, animated: true, completion: nil) 
      } 
     } 
    } 
    else { 
     // is a view controller 
     rootController.present(alert, animated: true, completion: nil) 
    } 
} 
+0

너무 감사 UINavigationController의 유형이나 UIViewController 인 경우는 rootController를 찾아 확인합니다! –

+0

@AntersBear 작동합니까? 정답으로 표시해주세요;) – xmhafiz