프로그래밍 방식으로 TabBar 탭보기로 전환 하시겠습니까?
UIButton
iPhone 앱에 하나의 탭보기가 있고의 탭 막대에서 다른 탭을 열고 싶다고 가정 해 봅시다 TabBarController
. 이를 위해 코드를 어떻게 작성합니까?
기존보기를 언로드하고 특정 탭보기를로드한다고 가정하지만 코드를 정확하게 작성하는 방법을 모르겠습니다.
Swift 또는 Objective-C에서이 코드를 사용해보십시오.
빠른
self.tabBarController.selectedIndex = 1
목표 -C
[self.tabBarController setSelectedIndex:1];
탭은 0부터 시작하여 색인화됩니다. 따라서 다음 코드 스 니펫이 작동합니다.
tabBarController = [[UITabBarController alloc] init];
.
.
.
tabBarController.selectedViewController = [tabBarController.viewControllers objectAtIndex:4];
막대의 다섯 번째 탭으로 이동합니다.
내 의견이다 selectedIndex
또는 사용이 objectAtIndex
탭을 전환 할 수있는 가장 좋은 방법은 필요하지 않습니다. 탭을 재정렬하면 하드 코딩 된 인덱스 선택으로 인해 이전 앱 동작이 엉망이 될 수 있습니다.
전환하려는 뷰 컨트롤러의 객체 참조가있는 경우 다음을 수행 할 수 있습니다.
tabBarController.selectedViewController = myViewController
물론 반드시 myViewController
의 목록에 있는지 확인해야합니다 tabBarController.viewControllers
.
selectedIndex
UITabBarController 의 속성을 적절한 인덱스로 설정하기 만하면 사용자가 탭 버튼을 탭한 것처럼보기가 변경됩니다.
나는 Disco S2가 제안한 것을 시도했지만 가까이 있었지만 이것이 나를 위해 일한 결과입니다. 다른 탭 내에서 작업을 완료 한 후 호출되었습니다.
for (UINavigationController *controller in self.tabBarController.viewControllers)
{
if ([controller isKindOfClass:[MyViewController class]])
{
[self.tabBarController setSelectedViewController:controller];
break;
}
}
탭을 이동할 수있는 경우 코드는 다음과 같습니다.
for ( UINavigationController *controller in self.tabBarController.viewControllers ) {
if ( [[controller.childViewControllers objectAtIndex:0] isKindOfClass:[MyViewController class]]) {
[self.tabBarController setSelectedViewController:controller];
break;
}
}
IB를 연결하는 방법에 덜 의존하는 강력한 솔루션을 생각하면서 인덱스 대신 클래스별로 표시되는 탭을 지정할 수 있기를 원했습니다. Disco 또는 Joped의 솔루션이 작동하지 않아서이 방법을 만들었습니다.
-(void)setTab:(Class)class{
int i = 0;
for (UINavigationController *controller in self.tabBarContontroller.viewControllers){
if ([controller isKindOfClass:class]){
break;
}
i++;
}
self.tabBarContontroller.selectedIndex = i;
}
당신은 이것을 다음과 같이 부릅니다.
[self setTab:[YourClass class]];
이것이 누군가에게 도움이되기를 바랍니다.
Stuart Clark의 솔루션과 같지만 Swift 3의 경우 :
func setTab<T>(_ myClass: T.Type) {
var i: Int = 0
if let controllers = self.tabBarController?.viewControllers {
for controller in controllers {
if let nav = controller as? UINavigationController, nav.topViewController is T {
break
}
i = i+1
}
}
self.tabBarController?.selectedIndex = i
}
Use it like this:
setTab(MyViewController.self)
Please note that my tabController links to viewControllers behind navigationControllers. Without navigationControllers it would look like this:
if let controller is T {
My issue is a little different, I need to switch from one childViewController in 1st tabBar to home viewController of 2nd tabBar. I simply use the solution provided in the upstairs:
tabBarController.selectedIndex = 2
However when it switched to the home page of 2nd tabBar, the content is invisible. And when I debug, viewDidAppear, viewWillAppear, viewDidLoad, none of them is called. My solutions is to add the following code in the UITabBarController:
override var shouldAutomaticallyForwardAppearanceMethods: Bool
{
return true
}
Use in AppDelegate.m
file:
(void)tabBarController:(UITabBarController *)tabBarController
didSelectViewController:(UIViewController *)viewController
{
NSLog(@"Selected index: %d", tabBarController.selectedIndex);
if (viewController == tabBarController.moreNavigationController)
{
tabBarController.moreNavigationController.delegate = self;
}
NSUInteger selectedIndex = tabBarController.selectedIndex;
switch (selectedIndex) {
case 0:
NSLog(@"click me %u",self.tabBarController.selectedIndex);
break;
case 1:
NSLog(@"click me again!! %u",self.tabBarController.selectedIndex);
break;
default:
break;
}
}
Like Stuart Clark's solution but for Swift 3 and using restoration identifier to find correct tab:
private func setTabById(id: String) {
var i: Int = 0
if let controllers = self.tabBarController?.viewControllers {
for controller in controllers {
if let nav = controller as? UINavigationController, nav.topViewController?.restorationIdentifier == id {
break
}
i = i+1
}
}
self.tabBarController?.selectedIndex = i
}
Use it like this ("Humans" and "Robots" must also be set in storyboard for specific viewController and it's Restoration ID, or use Storyboard ID and check "use storyboard ID" as restoration ID):
struct Tabs {
static let Humans = "Humans"
static let Robots = "Robots"
}
setTabById(id: Tabs.Robots)
Please note that my tabController links to viewControllers behind navigationControllers. Without navigationControllers it would look like this:
if controller.restorationIdentifier == id {
import UIKit
class TabbarViewController: UITabBarController,UITabBarControllerDelegate {
//MARK:- View Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
//Tabbar delegate method
override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
let yourView = self.viewControllers![self.selectedIndex] as! UINavigationController
yourView.popToRootViewController(animated:false)
}
}
참고URL : https://stackoverflow.com/questions/5413538/switching-to-a-tabbar-tab-view-programmatically
'Programing' 카테고리의 다른 글
두 번째로 큰 값을 찾는 가장 간단한 SQL 쿼리는 무엇입니까? (0) | 2020.06.09 |
---|---|
스칼라에서 파일에 쓰는 방법? (0) | 2020.06.09 |
NoneType 객체에 단위 테스트의 assertRaises ()를 올바르게 사용하는 방법은 무엇입니까? (0) | 2020.06.09 |
pandas dataframe에서 html로 변환 할 때 html로 전체 (잘리지 않은) 데이터 프레임 정보를 표시하는 방법은 무엇입니까? (0) | 2020.06.09 |
날짜에 하루 추가 (0) | 2020.06.09 |