2
내 코드를 조금 관리/단축하기 위해 모든 경고를 관리하는 도우미 클래스를 만들려고했습니다.SWIFT - 헬퍼 클래스 콜백
아이디어는 도우미 클래스가 경고를 생성한다는 것입니다. 사용자가 버튼을 누를 때 어떤 버튼이 눌려 졌는지 viewController의 코드에 알리기 위해 콜백을 보냅니다. 그럼 그 코드에 따라 다른 비트를 발사 할 수 있습니다.
현재 경고 코드를 올바르게 표시하는 코드는 있지만 버튼을 누르면 콜백을 보낼 수 없습니다.
let titleTxt:String = "title txt goes here."
let confirmTxt:String = "confirm"
let cancelTxt:String = "cancel"
let msgTxt:String = "some msg goes here."
let showCancel:Bool = true
let showConfirm:Bool = true
let style:UIAlertControllerStyle = .ActionSheet
let alert = alertMgr.showAlert(titleTxt, confirmText: confirmTxt, cancelText: cancelTxt, msgText: msgTxt, showCancel: showCancel, showConfirm: showConfirm, style:style, viewController: self)
switch alert as Int! {
case nil:
println("nil value")
case 0:
println("cancel pressed") //never gets fired. when button is pressed
case 1:
println("confirm pressed") //never gets fired. when button is pressed
default:
break
}
: 나는 다음 코드를 사용하여 경고를 표시 할 때
var alertMgr: alertManager = alertManager()
class alertManager: NSObject {
func showAlert(titleText:String?, confirmText:String, cancelText:String, msgText:String, showCancel:Bool, showConfirm:Bool, style:UIAlertControllerStyle, viewController:UIViewController) -> Int? {
let alertController = UIAlertController(title: titleText, message: msgText, preferredStyle: style)
var myInt:Int!
let actionLeft = UIAlertAction(title:cancelText, style: .Cancel) { action in
println("0") //works when user presses cancel button
myInt = 0
}
let actionRight = UIAlertAction(title:confirmText, style: .Default) { action in
println("1") //works when user presses confirm button
myInt = 1
}
alertController.addAction(actionLeft)
alertController.addAction(actionRight)
viewController.presentViewController(alertController, animated: true, completion: nil)
return myInt //does not return when button is pressed???
}
}
내 코드에서 : 여기
내 경고 관리자는 지금까지 (여전히 기본적인 편의를 위해) 생성 주요 문제는 버튼을 눌렀을 때 "myInt"값을 보내기 위해 콜백을 되돌릴 수없는 것입니다. 나는 여기서 [UIAlertController]에 대한 모든 질문을 검색했으며 올바른 방향으로 나를 밀어 붙일 수있는 힌트를 찾을 수 없었다.어떤 도움도 좋은 것입니다.
답장을 보내 주셔서 감사합니다. 100 % 이해할 수 없다는 것을 이해하고 있습니다. 더 나은 이해를 돕기 위해 샘플 코드를 게시 할 수 있습니까? 그 동안 나는 주위를 돌며 알아낼 수 있는지 알아볼 것입니다. 고마워 :) –
'actionLeft'와'actionRight' 블록은 사용자가 버튼을 눌렀을 때 호출되지만,'showAlert' 함수는 즉시 리턴합니다 - 쓸모가 없으므로 반환 값을 제거 할 수 있습니다. 대신'UIAlertAction' 타입의 두 매개 변수를 사용하여'actionLeft'와'actionRight'을 대체 할 수 있습니다. 블록과 클로저 사이에는 차이점이 있습니다. 공식 문서에서 자세한 내용을 읽을 수 있습니다. 어쨌든 접근 방식은 같습니다. 함수/클로저 프로토 타입의 예로서 클로저를 사용하는 표준 메서드를 사용할 수 있습니다. UIView + animateWithDuration : 지연 : 옵션 : 애니메이션 : 완료 : ' –
조금 혼란 스러울 수도 있습니다. 따라서 showAlert :에서 return을 제거하고 actionLeft/actionRight를 두 개의 UIAlertAction 매개 변수로 바꿉니다. 내 VC에 콜백은 어디에서 발생합니까? (그래서 확인/취소를 기반으로 다음 코드를 실행할 수 있습니다.) 약간의 손실이 여기에서 있습니다. 추신 : 나는 블록/클로저에 대해서 조금 더 읽었다. 하지만 여전히 이것을 보지 못한다. –