Overview

近期在开发中遇到一个奇葩异常:Cannot modify constraints for UITabBar managed by a controller。

结论

自动布局只能使用在UIViews及其子类,也就是说工具栏之类的不能使用。

原因

给UITabbarController的tabbar addSubView子视图(即红色线条那块),然后给子视图设置约束导致的。

    self.bottomLineView = [[UIView alloc] init];
    self.bottomLineView.backgroundColor = RGB_HEX(0xcc5253);
    [self.tabBar addSubview:self.bottomLineView];

    [self.bottomLineView makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.tabBar);
        make.width.equalTo(self.bottomLineViewWidth);
        make.top.equalTo(self.tabBar);
        make.height.equalTo(3);
    }];

查阅api发现

// Provided for -[UIActionSheet showFromTabBar:]. Attempting to modify the contents of the tab bar directly will throw an exception.

//提供-[UIActionSheet showFromTabBar:]。尝试直接修改选项卡栏的内容将抛出异常。

解决办法

    self.bottomLineView = [[UIView alloc] initWithFrame:CGRectMake(0, -3, self.bottomLineViewWidth, 3)];
    self.bottomLineView.backgroundColor = RGB_HEX(0xcc5253);
    [self.tabBar addSubview:self.bottomLineView];

即把autolayout改为传统的计算frame。