Method of removing left and right gaps in IOS 11 UI navigationitem

Time:2021-4-17

preface

Due to the change of Nav hierarchy in IOS 11, the previous method can not achieve the ideal mobile effect, so that the top button is completely left or right

Revise ideas

Before IOS 11, keep the original way to set, after IOS 11, modify the extra margin constraint to achieve the moving effect

From the view debug interface, you can see that you need to change the constraint of 16 on the left and right of uibutton barstack view to 0

Core code

Configure navigator view code

//0:leftBarButtonItems,1:rightBarButtonItems
- (void)initBarItem:(UIView*)view withType:(int)type{
  UIBarButtonItem * buttonItem = [[UIBarButtonItem alloc]initWithCustomView:view];
  //Solve the problem that the button is not left or right. IOS 11 system needs to be handled separately
  UIBarButtonItem * spaceItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
  spaceItem.width  =- 16; // this value can be adjusted according to your own needs
  switch (type) {
    case 0:
      if (!IS_IOS_VERSION_11) {
        self.navigationItem.leftBarButtonItems [email protected][spaceItem,buttonItem];
      }else{
        self.navigationItem.leftBarButtonItems [email protected][buttonItem];
      }
      break;
    case 1:
      if (!IS_IOS_VERSION_11) {
        self.navigationItem.rightBarButtonItems [email protected][spaceItem,buttonItem];
      }else{
        self.navigationItem.rightBarButtonItems [email protected][buttonItem];
      }
      break;
      
    default:
      break;
  }
}

To deal with the offset problem in the case of ios11, change the value of the constraint with the margin of 16 to 0

-(void)viewDidLayoutSubviews{
  if (!IS_IOS_VERSION_11) return;
  UINavigationItem * item=self.navigationItem;
  NSArray * array=item.leftBarButtonItems;
  if (array&&array.count!=0){
    //It should be noted that the customeview of the first leftbarbuttonitem you set cannot be empty, that is, do not set uibarbuttons systemitemfixedspace style items
    UIBarButtonItem * buttonItem=array[0];
    UIView * view =[[[buttonItem.customView superview] superview] superview];
    NSArray * arrayConstraint=view.constraints;
    for (NSLayoutConstraint * constant in arrayConstraint) {
      if (fabs(constant.constant)==16) {
        constant.constant=0;
      }
    }
  }
}

The effect after modification.png

Demo address: https://github.com/StoneMover/navDemo.git

The above is the whole content of this article, I hope to help you learn, and I hope you can support developer more.