Swift: как показать контроллер панели вкладок после просмотра входа в систему
Я видел много сообщений, похожих на это здесь, но они все о Objective-C, пока я разрабатываю свое приложение в Swift. Как видно из изображения, у меня есть вид экрана входа в систему, и я правильно реализовал механизм входа.
![введите описание изображения здесь]()
Теперь я хотел бы, чтобы при входе в систему было подтверждено, что отображается контроллер панели вкладок. В моем контроллере входа в систему у меня есть эта функция для входа в систему:
var finalURL:NSString = "\(Settings.webServerLoginURL)?username=\(username)&password=\(password)"
LoginService.requestLoginWithURL(NSURL(string: finalURL as String)!, completionHandler: { (success) -> Void in
if (success) {
NSLog("Login OK")
/* Scarica dal database i tasks di LoggedUser.id */
/* Redirect al tab HOME dell'applicazione dove si mostrano il numero di task
di quell'utente ed in cima "BENVENUTO: name surname" */
}
else {
self.alertView.title = "Autenticazione fallita!"
self.alertView.message = "Username o passowrd."
self.alertView.delegate = self
self.alertView.addButtonWithTitle("OK")
self.alertView.show()
}
Итак, я думаю, что я должен показать контроллер панели вкладок после
NSLog("Login OK")
но я не знаю, как это сделать. Я новичок Swift/XCode... если вы можете мне объяснить.
Спасибо всем, кто прочитал.
Ответы
Ответ 1
Чтобы отобразить контроллер панели вкладок со страницы входа, подключите страницу входа и TabbarController с помощью Show segue и дайте ему идентификатор в инспекторе атрибутов (скажите "mySegueIdentifier" ).
Чтобы добавить segue, просто щелкните правой кнопкой мыши и перетащите его с контроллера входа в панель TabbarController.
В успешном Логин вы можете просто вызвать метод executeSegueWithIdentifier следующим образом
self.performSegueWithIdentifier("mySegueIdentifier", sender: nil)
В этом случае вы вызываете его после этой строки.
NSLog("Login OK")
Если вы не хотите перемещаться со страницы входа в TabbarController, вы также можете установить ее как rootViewController после успешного входа в систему.
Для этого установите идентификатор TabbarController (скажем "myTabbarController" )
let appDelegate = UIApplication.sharedApplication().delegate! as! AppDelegate
var initialViewController = self.storyboard!.instantiateViewControllerWithIdentifier("myTabbarControllerID") as! UIViewController
appDelegate.window?.rootViewController = initialViewController
appDelegate.window?.makeKeyAndVisible()
Edit:
Swift 3
let appDelegate = UIApplication.shared.delegate! as! AppDelegate
let initialViewController = self.storyboard!.instantiateViewController(withIdentifier: "myTabbarControllerID")
appDelegate.window?.rootViewController = initialViewController
appDelegate.window?.makeKeyAndVisible()
Счастливое кодирование..:)
Ответ 2
Я столкнулся с этой же проблемой при попытке перейти от контроллера, который я использовал для touchID к TabBarController. Сделав segue в асинхронном блоке, я решил проблему.
dispatch_async(dispatch_get_main_queue(), {
self.dismissViewControllerAnimated(false, completion: {})
self.performSegueWithIdentifier("authnToAppSegue", sender: nil)
})
Ответ 3
Дайте вашему контроллеру панели вкладок StoryboardID (скажем, "tabbar") и нажмите его, как обычный UIViewController:
let nextViewController = self.storyboard?.instantiateViewController(withIdentifier: "tabbar") as! UIViewController
self.navigationController?.pushViewController(nextViewController, animated: true)
Ответ 4
func setTabBarVisible(visible:Bool, animated:Bool) {
//* This cannot be called before viewDidLayoutSubviews(), because the frame is not set before this time
// bail if the current state matches the desired state
if (tabBarIsVisible() == visible) { return }
// get a frame calculation ready
let frame = self.tabBarController?.tabBar.frame
let height = frame?.size.height
let offsetY = (visible ? -height! : height)
// zero duration means no animation
let duration:NSTimeInterval = (animated ? 0.3 : 0.0)
// animate the tabBar
if frame != nil {
UIView.animateWithDuration(duration) {
self.tabBarController?.tabBar.frame = CGRectOffset(frame!, 0, offsetY!)
return
}
}
}
func tabBarIsVisible() ->Bool {
return self.tabBarController?.tabBar.frame.origin.y < CGRectGetMaxY(self.view.frame)
}
// Call the function from tap gesture recognizer added to your view (or button)
@IBAction func tapped(sender: AnyObject) {
setTabBarVisible(!tabBarIsVisible(), animated: true)
}
Ответ 5
Вызов контроллера Tabbar из любого контроллера. В соответствии с кодом ниже, выбран первый элемент по умолчанию
let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
let nextViewController = storyBoard.instantiateViewController(withIdentifier: "HomeTabBar") as! UITabBarController
self.navigationController?.pushViewController(nextViewController, animated: true)