programing

프로그래밍 방식으로 다른 보기 컨트롤러/장면으로 이동

bestprogram 2023. 9. 9. 09:46

프로그래밍 방식으로 다른 보기 컨트롤러/장면으로 이동

첫 번째 보기 컨트롤러에서 두 번째 보기 컨트롤러로 이동하는 동안 오류 메시지가 발생했습니다.제 코딩은 이런 거예요.

let vc = LoginViewController(nibName: "LoginViewController", bundle: nil)
self.navigationController?.pushViewController(vc, animated: true)

문제는 제가 항상 이런 오류 메시지를 받았다는 것입니다.

2014-12-09 16:51:08.219 XXXXX[1351:60b] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Could not load NIB in bundle: 'NSBundle </var/mobile/Applications/FDC7AA0A-4F61-47E7-955B-EE559ECC06A2/XXXXX.app> (loaded)' with name 'LoginViewController''
*** First throw call stack:
(0x2efcaf0b 0x39761ce7 0x2efcae4d 0x31b693f9 0x31ac1eaf 0x3191e365 0x317fe895 0x318a930d 0x318a9223 0x318a8801 0x318a8529 0x318a8299 0x318a8231 0x317fa305 0x3147631b 0x31471b3f 0x314719d1 0x314713e5 0x314711f7 0x3146af1d 0x2ef96039 0x2ef939c7 0x2ef93d13 0x2eefe769 0x2eefe54b 0x33e6b6d3 0x3185d891 0x4ccc8 0x4cd04 0x39c5fab7)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)

나는 이미 답을 찾았습니다.

스위프트 4

let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
let nextViewController = storyBoard.instantiateViewController(withIdentifier: "nextView") as! NextViewController
self.present(nextViewController, animated:true, completion:nil)

스위프트 3

let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)

let nextViewController = storyBoard.instantiateViewControllerWithIdentifier("nextView") as NextViewController
self.presentViewController(nextViewController, animated:true, completion:nil)

이거 드셔보세요.여기 "LoginViewController"는 스토리보드입니다.스토리보드에 ID가 지정되어 있습니다.

아래참조

let secondViewController = self.storyboard?.instantiateViewControllerWithIdentifier("LoginViewController") as LoginViewController
self.navigationController?.pushViewController(secondViewController, animated: true)

XCODE 8.2 및 스위프트 3.0

존재를 제시합니다.UIViewController

let loginVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "LoginViewController") as! LoginViewController
self.present(loginVC, animated: true, completion: nil)

존재를 누름UIViewController

let loginVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "LoginViewController") as! LoginViewController
self.navigationController?.pushViewController(loginVC, animated: true)

당신은 당신이 그 위에 두어도 된다는 것을 기억하세요.UIViewController다음 단계를 따르는 식별자:

  • 선택한다.Main.storyboard
  • 선택합니다.UIViewController
  • 오른쪽에서 유틸리티 검색
  • ID 검사자를 선택합니다.
  • 섹션 ID "Storyboard ID"에서 검색
  • 사용자의 ID를 입력합니다.UIViewController

enter image description here

Controller created Programmatic으로 이동하려면 다음 작업을 수행합니다.

let newViewController = NewViewController()
self.navigationController?.pushViewController(newViewController, animated: true)

식별자 "newViewController"가 있는 StoryBoard의 Controller로 이동하려면 다음 작업을 수행합니다.

let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let newViewController = storyBoard.instantiateViewController(withIdentifier: "newViewController") as! NewViewController
        self.present(newViewController, animated: true, completion: nil)

스위프트3:

let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewController("LoginViewController") as UIViewController
self.navigationController?.pushViewController(vc, animated: true)

이거 한번 해보세요.당신은 방금 스토리보드 표현과 nib을 혼동했습니다.

아래 코드를 사용하여 한 장면에서 다른 장면으로 프로그래밍 방식으로 이동할 수 있습니다.

  let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)

  let objSomeViewController = storyBoard.instantiateViewControllerWithIdentifier(“storyboardID”) as! SomeViewController

  // If you want to push to new ViewController then use this
  self.navigationController?.pushViewController(objSomeViewController, animated: true)

  // ---- OR ----

  // If you want to present the new ViewController then use this
  self.presentViewController(objSomeViewController, animated:true, completion:nil) 

여기 스토리보드ID는 Interface Builder를 사용하여 씬(scene)으로 설정한 값입니다.이 내용은 다음과 같습니다.

Screenshot for how to set storyboardID

내 거 봐요.

func actioncall () {
    let loginPageView = self.storyboard?.instantiateViewControllerWithIdentifier("LoginPageID") as! ViewController
    self.navigationController?.pushViewController(loginPageView, animated: true)
}

프리젠테이션 스타일을 사용할 경우, 미리 설정된 푸시 탐색으로 페이지의 탐색 표시줄이 손실될 수 있습니다.

프로그래밍적으로 다른 상황에 따라 다른 방법이 있습니다.

  1. load story 코드 입력 여기보드 nib 파일

    let yourVc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "YourViewController") as! YourViewController;
    self.present(yourVc, animated: true, completion: nil)
    
  2. xib에서 로드

    let yourVc = YourViewController.init(nibName: "YourViewController", bundle: nil)
    self.present(yourVc, animated: true, completion: nil)
    
  3. Segue를 탐색합니다.

    self.performSegue(withIdentifier: "your UIView", sender: self)
    
let VC1 = self.storyboard!.instantiateViewController(withIdentifier: "MyCustomViewController") as! ViewController
let navController = UINavigationController(rootViewController: VC1)
self.present(navController, animated:true, completion: nil)

XCODE 9.2 및 스위프트 3.0

ViewController로.NextViewcontrollerSegue Connection 없이

let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
let nextViewController = storyBoard.instantiateViewController(withIdentifier: "NextViewController") as! NextViewController
self.navigationController?.pushViewController(nextViewController, animated:true)

아니면

let VC:NextViewController = storyboard?.instantiateViewController(withIdentifier: "NextViewController") as! NextViewController
self.navigationController?.pushViewController(VC, animated: true)

보기컨트롤러의 스토리보드와 스토리보드아이디의 도움으로 코드를 사용하여 보기컨트롤러 간의 탐색을 수행할 수 있습니다.이 코드는 스위프트 3:

let signUpVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "SignUp")
self.navigationController?.pushViewController(signUpVC, animated: true)

당신의 앱에서 당신의 화면 위에 네비게이션 뷰 컨트롤러를 설정할 수 있는 위의 좋은 답변 외에, 당신은 다음과 같이 당신의 AppDelegate.swift 파일에 그것을 추가할 수 있습니다.

 func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

    window = UIWindow()
    window?.makeKeyAndVisible()
    window?.rootViewController = UINavigationController(rootViewController: LoginViewController())

    return true

}
 let vc = DetailUserViewController()
 vc.userdetails = userViewModels[indexPath.row]
 self.navigationController?.pushViewController(vc, animated: true)

아래 단계에서 시도해 볼 수 있을지 모르겠습니다. 아래 이유에서 오류가 발생할 수도 있습니다.

  • XCode 외부의 일부 파일 이름을 바꿉니다.이를 해결하려면 프로젝트에서 파일을 제거하고 프로젝트의 파일을 다시 가져옵니다.
  • 빌드 단계 -> 번들 리소스 복사에서 누락된 Nib 파일을 확인하고 추가합니다.마지막으로 nib 이름 철자를 확인합니다. 정확합니다. 대소문자 구분입니다.
  • 파일 검사기에서 .xib/storyboard 파일의 속성을 확인하고 선택 상자의 속성 "Target Membership" 피치를 선택한 다음 xib/storyboard 파일이 대상과 연결되었습니다.
  • NIB의 잘못된 유형과 같은.파일을 마우스 오른쪽 단추로 클릭하고 "Get Info"를 클릭하여 유형이 예상되는 유형인지 확인합니다.

전환을 위한 암호를 알려드립니다.이 예에서는 UI 버튼에 작업을 연결하고 있습니다.그러니 잊지 말고 세팅해주세요.의는을지오e지e에서 View Controller의 이름을 설정하는 것도 마십시오transition방법.

스토리보드 세팅하는 것도 잊지 마세요.뷰 컨트롤러당 하나의 뷰가 있어야 합니다.각 보기 컨트롤러를 스토리보드의 각 보기에 연결합니다.아래 스크린샷을 보시면 알 수 있습니다.

enter image description here enter image description here

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

         var playButton   = UIButton.buttonWithType(UIButtonType.System) as UIButton

         let image = UIImage(named: "YourPlayButton") as UIImage?

         playButton.frame = CGRectMake(0, 0, 100, 100)
         playButton.center = CGPointMake(self.view.frame.width/2, self.view.frame.height/2)
         playButton.addTarget(self, action: "transition:", forControlEvents:  UIControlEvents.TouchUpInside)
         playButton.setBackgroundImage(image, forState: UIControlState.Normal)

         self.view.addSubview(playButton)
    }


func transition(sender:UIButton!)
{
    println("transition")
    let secondViewController = self.storyboard?.instantiateViewControllerWithIdentifier("YourSecondViewController") as UIViewController

    let window = UIApplication.sharedApplication().windows[0] as UIWindow
    UIView.transitionFromView(
        window.rootViewController!.view,
        toView: secondViewController.view,
        duration: 0.65,
        options: .TransitionCrossDissolve,
        completion: {
            finished in window.rootViewController = secondViewController
    })
}
}

드래그 앤 드롭 없이(스토리보드를 사용하지 않고) UI를 만들고 있고 기본 페이지 또는 ViewController.swift를 다른 페이지로 이동하려면?이 단계를 따릅니다. 1) 클래스 추가(.swift) 2) UIKit 가져오기 3) 클래스 이름을 다음과 같이 선언합니다.

class DemoNavigationClass :UIViewController{
     override func viewDidLoad(){
         let lbl_Hello = UILabel(frame: CGRect(x:self.view.frame.width/3, y:self.view.frame.height/2, 200, 30));
lbl_Hello.text = "You are on Next Page"
lbl_Hello.textColor = UIColor.white
self.view.addSubview(lbl_Hello)
    }
}

두 번째 페이지를 만든 후 첫 번째 페이지로 돌아갑니다(ViewController.swift) 여기서 viewDidLoad 메서드의 버튼을 만듭니다.

let button = UIButton()
button.frame = (frame: CGRect(x: self.view.frame.width/3, y: self.view.frame.height/1.5,   width: 200, height: 50))
 button.backgroundColor = UIColor.red
 button.setTitle("Go to Next ", for: .normal)
 button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
 self.view.addSubview(button)

이제 정의 buttonAction method of view DidLoad()를 같은 클래스에 정의합니다.

func buttonAction(sender: UIButton!) 
{
    let obj : DemoNavigationClass = DemoNavigationClass();
    self.navigationController?.pushViewController(obj, animated: true)
}

메인에 한가지 잊어버린것이 있습니다. 스토리보드에 화살표가 있는 장면이 있습니다. 그 화살표를 선택하고 삭제 버튼을 누릅니다.

이제 탐색 컨트롤러를 드래그 앤 드롭하고 탐색 컨트롤러와 함께 제공되는 테이블 뷰를 삭제합니다. 키보드에서 탐색 컨트롤러 누르기 컨트롤을 선택하고 스토리보드의 다른 장면인 View Controller로 드래그합니다.이것은 당신의 뷰 컨트롤러가 루트 뷰 컨트롤러가 되기를 바란다는 것을 의미합니다. 메인.스토리보드, 드래그 앤 드롭 내비게이션 컨트롤러,

let signUpVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "SignUp")
// self.present(signUpVC, animated: false, completion: nil)
self.navigationController?.pushViewController(signUpVC, animated: true)

스위프트 4.0.3

 @IBAction func registerNewUserButtonTapped(_ sender: Any) {

        print("---------------------------registerNewUserButtonTapped --------------------------- ");

        let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)

        let nextViewController = storyBoard.instantiateViewController(withIdentifier: "RegisterNewUserViewController") as! RegisterNewUserViewController
        self.present(nextViewController, animated:true, completion:nil)

    }

컨트롤러 이름 변경등록새 사용자 보기컨트롤러

이런 걸 찾고 계신 것 같습니다.

let signUpViewController = SignUpViewController()
present(signUpViewController, animated: true, completion: nil)

새 페이지의 전체 화면을 원하는 경우:

present(signUpViewController, animated: true, completion: nil)

도움이 되길 바라요 :)

let vc = storyboard?.instantiateViewController(withIdentifier: "make sure you give id to screen")as! screenviewclass
        self.navigationController?.pushViewController(vc, animated: true)

언급URL : https://stackoverflow.com/questions/27374759/programmatically-navigate-to-another-view-controller-scene