Swift를 사용하여 iOS에서 프로그래밍 방식으로 설정하는 방법
Facebook SDK를 사용하여 사용자를 인증하는 앱을 만들고 있습니다.페이스북 논리를 다른 클래스로 통합하려고 합니다.다음은 코드입니다(간단함을 위해 줄 바꿈).
import Foundation
class FBManager {
class func fbSessionStateChane(fbSession:FBSession!, fbSessionState:FBSessionState, error:NSError?){
//... handling all session states
FBRequestConnection.startForMeWithCompletionHandler { (conn: FBRequestConnection!, result: AnyObject!, error: NSError!) -> Void in
println("Logged in user: \n\(result)");
let storyboard = UIStoryboard(name: "Main", bundle: NSBundle.mainBundle())
let loggedInView: UserViewController = storyboard.instantiateViewControllerWithIdentifier("loggedInView") as UserViewController
loggedInView.result = result;
//todo: segue to the next view???
}
}
}
세션 상태 변화를 확인하기 위해 위의 클래스 방법을 사용하고 있으며, 정상적으로 작동합니다.
Q: 사용자 데이터를 얻으면 이 커스텀클래스 내에서 다음 보기로 이동하려면 어떻게 해야 하나요?
참고로 스토리보드에 식별자가 있는 segue가 있는데 뷰 컨트롤러가 아닌 클래스에서 segue를 실행하는 방법을 찾고 있습니다.
두 뷰 사이에 segue 식별자가 있는 스토리보드에 segue가 있는 경우 다음을 사용하여 프로그래밍 방식으로 호출할 수 있습니다.
performSegue(withIdentifier: "mySegueID", sender: nil)
이전 버전의 경우:
performSegueWithIdentifier("mySegueID", sender: nil)
다음 작업도 가능합니다.
presentViewController(nextViewController, animated: true, completion: nil)
또는 내비게이션 컨트롤러에 있는 경우:
self.navigationController?.pushViewController(nextViewController, animated: true)
두 뷰 사이에 segue 식별자가 있는 스토리보드에 segue가 있는 경우 를 사용하여 프로그래밍 방식으로 호출할 수 있습니다.
self.performSegueWithIdentifier("yourIdentifierInStoryboard", sender: self)
내비게이션 컨트롤러에 있는 경우
let viewController = YourViewController(nibName: "YourViewController", bundle: nil)
self.navigationController?.pushViewController(viewController, animated: true)
네비게이션 컨트롤러를 이용한 두 번째 접근을 추천합니다.
NSNotification을 사용할 수 있습니다.
커스텀 클래스에 포스트 메서드를 추가합니다.
NSNotificationCenter.defaultCenter().postNotificationName("NotificationIdentifier", object: nil)
View Controller에 옵서버를 추가합니다.
NSNotificationCenter.defaultCenter().addObserver(self, selector: "methodOFReceivedNotication:", name:"NotificationIdentifier", object: nil)
View Controller에 기능 추가:
func methodOFReceivedNotication(notification: NSNotification){
self.performSegueWithIdentifier("yourIdentifierInStoryboard", sender: self)
}
segue는 다음과 같이 사용할 수 있습니다.
self.performSegueWithIdentifier("push", sender: self)
override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
if segue.identifier == "push" {
}
}
Swift 3 - SpriteKit에도 대응
NSNotification을 사용할 수 있습니다.
예:
1) 스토리보드에 segue를 만들고 식별자를 "segue"로 지정합니다.
2) 원하는 View Controller에 함수를 만듭니다.
func goToDifferentView() {
self.performSegue(withIdentifier: "segue", sender: self)
}
3) ViewController의 ViewDidLoad()에서 옵서버를 작성하지 않도록 합니다.
NotificationCenter.default.addObserver(self, selector: #selector(goToDifferentView), name: "segue" as NSNotification.Name, object: nil)
업데이트 - 마지막으로 이것을 사용했을 때,.addObserver
다음 코드를 호출하여 오류를 잠재웁니다.
NotificationCenter.default.addObserver(self, selector: #selector(goToDifferentView), name: NSNotification.Name(rawValue: "segue"), object: nil)
4. segue를 트리거할 위치에 ViewController 또는 Scene에서 Post Method를 추가합니다.
NotificationCenter.default.post(name: "segue" as NSNotification.Name, object: nil)
업데이트 - 마지막으로 이것을 사용했을 때,.post
다음 코드를 호출하여 오류를 잠재웁니다.
NotificationCenter.default.post(NSNotification(name: NSNotification.Name(rawValue: "segue"), object: nil) as Notification)
위에 이미 좋은 답변들이 있는데, 저는 segue를 하기 전에 준비에 조금 초점을 맞추고 싶습니다.
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.destination is YourDestinationVC {
let vc = segue.destination as? YourDestinationVC
// "label" and "friends" are part of destinationVC
vc?.label = "someText"
vc?.friends = ["John","Mike","Garry"]
}
수신처에 전달하고 싶은 데이터 처리가 완료됩니다.다음으로 VC는 적절한 장소에서 segue를 수행합니다.StoryBoard ID 필드의 StoryBoard Identity Inspector에서 "Identifier Of Destination VC"를 설정할 수 있습니다.
performSegue(withIdentifier: "IdentifierOfDestinationVC", sender: nil)
유닛 테스트에서는 당신이 무엇을 하고 싶은지가 매우 중요합니다.기본적으로 뷰 컨트롤러에서 작은 로컬 기능을 만들어야 합니다.함수의 이름을 아무것이나 붙이십시오.performSegueWithIndentifier
.
func localFunc() {
println("we asked you to do it")
performSegueWithIdentifier("doIt", sender: self)
}
다음으로 유틸리티 클래스를 변경합니다.FBManager
함수의 인수를 사용하는 이니셜라이저와 segue를 수행하는 ViewController의 함수를 유지하는 변수를 포함합니다.
public class UtilClass {
var yourFunction : () -> ()
init (someFunction: () -> ()) {
self.yourFunction = someFunction
println("initialized UtilClass")
}
public convenience init() {
func dummyLog () -> () {
println("no action passed")
}
self.init(dummyLog)
}
public func doThatThing() -> () {
// the facebook login function
println("now execute passed function")
self.yourFunction()
println("did that thing")
}
}
(편의성 초기화 기능을 사용하면 segue를 실행하지 않고 장치 테스트에서 이 기능을 사용할 수 있습니다.)
마지막으로, //to: 다음 뷰로 넘어갑니까??, 다음과 같은 방식으로 무언가를 배치합니다.
self.yourFunction()
유닛 테스트에서는 다음과 같이 호출할 수 있습니다.
let f = UtilClass()
f.doThatThing()
do That Thing은 fbsession 상태 변경 및UtilClass
FBManager 입니다.
실제 코드는 그냥 통과해 주세요.localFunc
(괄호 없음)를 FBManager 클래스로 지정합니다.
이건 나한테 효과가 있었어.
우선, 스토리보드의 뷰 컨트롤러에, ID 인스펙터내의 스토리보드 ID 를 지정합니다.그런 다음 다음 예제 코드를 사용합니다(클래스, 스토리보드 이름 및 스토리보드 ID가 사용 중인 것과 일치하는지 확인).
let viewController:
UIViewController = UIStoryboard(
name: "Main", bundle: nil
).instantiateViewControllerWithIdentifier("ViewController") as UIViewController
// .instantiatViewControllerWithIdentifier() returns AnyObject!
// this must be downcast to utilize it
self.presentViewController(viewController, animated: false, completion: nil)
상세한 것에 대하여는, http://sketchytech.blogspot.com/2012/11/instantiate-view-controller-using.html 를 참조해 주세요.
또 다른 옵션은 modal segue를 사용하는 것입니다.
1단계: 스토리보드로 이동하여 뷰 컨트롤러에 스토리보드 ID를 지정합니다.스토리보드 ID를 변경하는 위치는 오른쪽에 있는 ID 검사기에서 확인할 수 있습니다.스토리보드 ID를 호출합니다.ModalViewController
2단계: '송신자' 뷰 컨트롤러를 엽니다(이것을 '송신자'라고 부릅니다).ViewController
)에 이 코드를 추가합니다.
public class ViewController {
override func viewDidLoad() {
showModalView()
}
func showModalView() {
if let mvc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "ModalViewController") as? ModalViewController {
self.present(mvc, animated: true, completion: nil)
}
}
}
여는 View Controller는ModalViewController
순서 3: ModalViewController를 닫으려면 이 컨트롤러를 추가합니다.
public class ModalViewController {
@IBAction func closeThisViewController(_ sender: Any?) {
self.presentingViewController?.dismiss(animated: true, completion: nil)
}
}
다음을 사용하여 이 작업을 수행할 수 있습니다.performSegueWithIdentifier
기능.
구문:
func performSegueWithIdentifier(identifier: String, sender: AnyObject?)
예:
performSegueWithIdentifier("homeScreenVC", sender: nil)
이 방법은 효과가 있었습니다.
//Button method example
@IBAction func LogOutPressed(_ sender: UIBarButtonItem) {
do {
try Auth.auth().signOut()
navigationController?.popToRootViewController(animated: true)
} catch let signOutError as NSError {
print ("Error signing out: %@", signOutError)
}
}
언급URL : https://stackoverflow.com/questions/27604192/how-to-segue-programmatically-in-ios-using-swift
'programing' 카테고리의 다른 글
워크시트 클래스의 ShowAllData 메서드가 실패했습니다. (0) | 2023.04.17 |
---|---|
하나의 파일을 제외한 모든 파일 이동 (0) | 2023.04.17 |
Javascript를 사용하여 HTML 테이블을 Excel로 내보내기 (0) | 2023.04.17 |
ASCII 파일 전체를 C++ std:: 문자열로 읽습니다. (0) | 2023.04.17 |
JavaScript에서는 큰따옴표와 작은따옴표가 서로 호환됩니까? (0) | 2023.04.17 |