subodh1989 subodh1989 - 6 months ago 22
Swift Question

perform segues to non default tab view controller modally different storyboard

I want to perform segue ( modally from one view controller to another tab viewcontroller). but the problem is it is loading the default(at index 0) view controller. here is the code :

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
if (segue.identifier == "toRateSegue") {

let nav = segue.destinationViewController as! UINavigationController

let svc = nav.topViewController as! RateViewController;
svc.cell = self.cellSelected
}

if (segue.identifier == "toChat") {
let tabIndex = 1
let segue = segue.destinationViewController as! UITabBarController

if let navVC = segue.viewControllers?[0] as? UINavigationController {
let vc = navVC.viewControllers.first as! CustomProfileViewController
vc.event = self.event

}

if let navVC = segue.viewControllers?[tabIndex] as? UINavigationController {
let vc = navVC.viewControllers.first as! ChatViewController
vc.event = self.event
print("Event is \(self.event.eventId)")
// if self is the event creator
if (self.userName == self.event.createdBy.objectForKey("username") as? String)
{


let query = PFQuery(className:"Event")
query.getObjectInBackgroundWithId(self.event.eventId!) {
(curevent: PFObject?, error: NSError?) -> Void in
if error == nil && curevent != nil {

let userObject:PFUser = curevent!["joinedBy"] as! PFUser

print("userObject.objectId \(userObject.objectId)")

vc.otherName = String(userObject.objectForKey("firstname")!)
vc.otherProfileName = String(userObject.objectForKey("firstname")!)
//print("vc.otherProfileName \(vc.otherProfileName)")
let senderuserName = PFUser.currentUser()!["username"] as? String
//print("senderuserName \(senderuserName)")

vc.roomid = self.event.geteventID() + vc.otherProfileName + senderuserName!

// print("roomid \(vc.roomid)")

} else {
print(error)
}

}

}else
{

vc.otherName = (self.event.createdBy.objectForKey("firstname") as? String)!
vc.otherProfileName = (self.event.createdBy.objectForKey("firstname") as? String)!
let senderuserName = PFUser.currentUser()!["username"] as? String

vc.roomid = event.geteventID() + senderuserName! + vc.otherProfileName

}


self.tabBarController?.selectedIndex = tabIndex

}
}

}


I am talking about toChat segue. It is called in tableview func as follows :

let connect = UITableViewRowAction(style: .Normal, title: "Connect") { action, index in

self.event = cell.event

self.performSegueWithIdentifier("toChat", sender: nil)



}`


I want to go to tab view at index 1 instead of index 0.

Answer

To move to a different tab in the UITabBarController, in prepareForSegue, set selectedIndex to 1 for the destinationViewController which is a UITabBarController:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if let dvc = segue.destinationViewController as? UITabBarController {
        dvc.selectedIndex = 1
    }
}
Comments