2017-12-12 2 views
0

내 응용 프로그램에 여러 개의보기 컨트롤러가 있습니다. 그리고 그들 각각에서 나는 어떤 조건들에 기초하여 경고를 보여 주어야합니다. 각각에 경고 컨트롤러를 추가하는 대신 다음과 같이 상속을 시도했습니다.UIViewController 및 상속

UIExtension.swift

class UIExtension: UIViewController { 

    func prepareAlert(title: String, message: String) -> UIAlertController { 
     let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert) 
     alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil)) 
     return alert 
    } 

} 

FirstViewController.swift 경보를 표시하기 위해 다른 viewcontrollers에 UIExtension 사용 마찬가지로

class FirstViewController: UIExtension { 

    //somewhere inside used the following 
    present(prepareAlert(title: "Error Validation", message: "invalid fields"), animated: true, completion: nil) 

} 

. 이 방법이 권장됩니까?

답변

2

이렇게하려면 prepareAlert 메서드를 UIViewController 확장자로 추가하는 것이 좋습니다. 서브 클래 싱은 필요 없습니다.

extension UIViewController { 
    func prepareAlert(title: String, message: String) -> UIAlertController { 
     let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert) 
     alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil)) 
     return alert 
    } 
} 

그런 다음보기 컨트롤러 :

class FirstViewController: UIViewController { 
    //somewhere inside used the following 
    present(prepareAlert(title: "Error Validation", message: "invalid fields"), animated: true, completion: nil) 
} 

이 어떤 뷰 컨트롤러에서 prepareAlert을 사용할 수 있습니다 포함 UITableViewController, UICollectionViewController

1

당신이 고려하는 경우 있지만 접근 방식은 기술적으로 정확 조건에 관계없이 모든 UIViewController 인스턴스를 확장하면 직접 확장하는 것이 더 편리합니다.

extension UIViewController { 
    func prepareAlert(title: String, message: String) -> UIAlertController { 
     let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert) 
     alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil)) 
     return alert 
    } 
} 

rmaddy가 빠릅니다. 그러나 나는 그 대답을 삭제하지 않기로 결정했으나 또 다른 생각을 추가하기로 결정했다.

또 다른 접근법은 프로토콜을 특정 기능의 래퍼로 사용하는 것이며, 이는 널리 사용됩니다.

말은, 당신이이 경우에 경고를 생성과 같은 일부 기능과 관련된 프로토콜이 : 특정 UIViewController 예를 원할 때마다, 그리고

protocol Alertable {} // or whatever else name 

extension Alertable { 
    func prepareAlert(title: String, message: String) -> UIAlertController { 
     let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert) 
     alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil)) 
     return alert 
    } 
} 

(또는 다른 클래스를, 당신은 아이디어를 얻을) 이 기능과 관련된 것으로, 간단하게 수행

class FirstViewController: UIViewController, Alertable { 
    // Now you can do the same: 

    present(prepareAlert(title: "Error Validation", message: "invalid fields"), animated: true, completion: nil) 

} 

그것으로 특정 클래스를 연결 한 다음 프로토콜을 구성하고 확장하고, 요약하면 - 그 기능을 노출하는 것은 - 매우 편리하고 유용한 방법입니다. 특히 이것은 일부 기능을 캡슐화하는 좋은 방법입니다 (예 : 전역/클래스 전체에 대한 액세스를 의미하지 않는 경우).

1

난 당신이 공유하고 일부 확장 방법을 사용하면 UIViewController 클래스의 어떤 곳에서 사용하고 :)

extension UIViewController { 
    let kAPPNAME = "Your App name" 

    func showOkAlert(_ msg: String) { 
     let alert = UIAlertController(title: 
      kAPPNAME, message: msg, preferredStyle: .alert) 
     let okAction = UIAlertAction(title: "OK", style: .default, handler: nil) 
     alert.addAction(okAction) 
     present(alert, animated: true, completion: nil) 
    } 

    func showOkAlertWithHandler(_ msg: String,handler: @escaping()->Void){ 
     let alert = UIAlertController(title: kAPPNAME, message: msg, preferredStyle: .alert) 
     let okAction = UIAlertAction(title: "OK", style: .default) { (type) -> Void in 
      handler() 
     } 
     alert.addAction(okAction) 
     present(alert, animated: true, completion: nil) 
    } 

    func showAlertWithActions(_ msg: String,titles:[String], handler:@escaping (_ clickedIndex: Int) -> Void) { 
     let alert = UIAlertController(title: kAPPNAME, message: msg, preferredStyle: .alert) 
     for title in titles { 
      let action = UIAlertAction(title: title, style: .default, handler: { (alertAction) in 
       //Call back fall when user clicked 
       let index = titles.index(of: alertAction.title!) 
       if index != nil { 
        handler(index!+1) 
       } 
       else { 
        handler(0) 
       } 
      }) 
      alert.addAction(action) 
     } 
     present(alert, animated: true, completion: nil) 
    } 

    func showOkCancelAlertWithAction(_ msg: String, handler:@escaping (_ isOkAction: Bool) -> Void) { 
     let alert = UIAlertController(title: kAPPNAME, message: msg, preferredStyle: .alert) 
     let okAction = UIAlertAction(title: "OK", style: .default) { (action) -> Void in 
      return handler(true) 
     } 
     let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { (action) -> Void in 
      return handler(false) 
     } 
     alert.addAction(cancelAction) 
     alert.addAction(okAction) 
     present(alert, animated: true, completion: nil) 
    } 
} 

class FirstViewController: UIViewController { 
     override func viewDidLoad() { 
     super.viewDidLoad() 

     //Only Info 
     self.showOkAlert("Hello") 

     //Info with Okay button 
     self.showOkAlertWithHandler("Hello Again") { 
      print("Tap to Okay") 
     } 

     //Show alert with Okay and cancel 
     self.showOkCancelAlertWithAction("Hello with Cancel") { (isOk) in 
      if isOk { 
       print("Okay") 
      } 
      else { 
       print("Cancel") 
      } 
     } 

     //Show alert with actions   
     self.showAlertWithActions("Hello with action", titles: ["Allow","Don't Allow", "Cancel"]) { (tapIndex) in 
      if tapIndex == 1 { 
       print("Allow") 
      } 
     } 
    } 
} 
을 사용하여 즐길 수있는 자주 대부분의 응용 프로그램에 사용됩니다