reason: 'Cannot modify constraints for UITabBar managed by a controller'

當在UITabBarController底部TabBar自定義的時候,我自定義了一個View,然後添加到系統自帶的tabBar上。因爲當APP打開時,我要任意切換橫屏和豎屏,所以我要讓自定義的tabBar適配屏幕。


我首先想到的方法是用masonry來做約束:

- (void)setupTabbar{


    WWTabBar *customTabBar = [[WWTabBaralloc] init];

    customTabBar.backgroundColor = [UIColorwhiteColor];

    customTabBar.delegate =self;

    [self.tabBaraddSubview:customTabBar];

    self.customTabBar = customTabBar;

    

    [customTabBar mas_makeConstraints:^(MASConstraintMaker *make) {

        

        make.top.equalTo(self.tabBar.mas_top);

        make.left.equalTo(self.tabBar.mas_left);

        make.bottom.equalTo(self.tabBar.mas_bottom);

        make.right.equalTo(self.tabBar.mas_right);

    }];

    

}


結果是程序剛一啓動,就崩潰了,跑出錯誤:

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Cannot modify constraints for UITabBar managed by a controller'


那麼,爲什麼會出現這種錯誤呢?

因爲​Autolayout只能對uiview和它的子類起作用。UIBarButtonItem不繼承自UIView,Autolayout對UIBarButtonItem不起作用。


解決辦法:

第一種方法:

- (void)setupTabbar{

    

    WWTabBar *customTabBar = [[WWTabBaralloc] init];

    customTabBar.backgroundColor = [UIColorwhiteColor];

    customTabBar.delegate =self;

    customTabBar.frame =self.tabBar.bounds;

    [self.tabBaraddSubview:customTabBar];

    self.customTabBar = customTabBar;

    

    customTabBar.autoresizingMask =UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleBottomMargin|UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleLeftMargin;

}


第二種辦法:在tabbar里加這個通知,橫屏時重新佈局一下(不建議)
 [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(changeRotate:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];

- (void)changeRotate:(NSNotification*)noti {
    if ([[UIDevice currentDevice] orientation] == UIInterfaceOrientationPortrait
        || [[UIDevice currentDevice] orientation] == UIInterfaceOrientationPortraitUpsideDown) {
       
        NSLog(@"豎屏");

    } else {
        
        NSLog(@"橫屏");
    }
}


好了,到這就就說完了,小夥伴們趕快試試吧。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章