iOS UINavigationItem去除左右间隙 iOS 11 UINavigationItem 去除左右间隙的方法

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

iOS UINavigationItem去除左右间隙 iOS 11 UINavigationItem 去除左右间隙的方法

stonemover   2021-03-29 我要评论
想了解iOS 11 UINavigationItem 去除左右间隙的方法的相关内容吗,stonemover在本文为您仔细讲解iOS UINavigationItem去除左右间隙的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:iOS11,去除左右间隙,iOS11,UINavigationItem,下面大家一起来学习吧。

前言

iOS 11版本由于对于Nav层级结构的改变,导致以前的方法无法达到理想的移动效果,使顶部的按钮完全靠左,或者是靠右.

修改思路

在iOS11之前保持原有方式进行设置,iOS11之后进行额外的边距约束修改达到移动效果.

从viewDebug的界面上观察可以看到需要将UIButtonBarStackView距离左边和右边的16的约束改为0即可.


核心代码

配置导航器view代码

//0:leftBarButtonItems,1:rightBarButtonItems
- (void)initBarItem:(UIView*)view withType:(int)type{
  UIBarButtonItem * buttonItem = [[UIBarButtonItem alloc]initWithCustomView:view];
  //解决按钮不靠左 靠右的问题.iOS 11系统需要单独处理
  UIBarButtonItem * spaceItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
  spaceItem.width = -16;//这个值可以根据自己需要自己调整
  switch (type) {
    case 0:
      if (!IS_IOS_VERSION_11) {
        self.navigationItem.leftBarButtonItems =@[spaceItem,buttonItem];
      }else{
        self.navigationItem.leftBarButtonItems =@[buttonItem];
      }
      break;
    case 1:
      if (!IS_IOS_VERSION_11) {
        self.navigationItem.rightBarButtonItems =@[spaceItem,buttonItem];
      }else{
        self.navigationItem.rightBarButtonItems =@[buttonItem];
      }
      break;
      
    default:
      break;
  }
}

处理iOS11情况下的偏移问题,将边距为16的约束的值改为0.

-(void)viewDidLayoutSubviews{
  if (!IS_IOS_VERSION_11) return;
  UINavigationItem * item=self.navigationItem;
  NSArray * array=item.leftBarButtonItems;
  if (array&&array.count!=0){
    //这里需要注意,你设置的第一个leftBarButtonItem的customeView不能是空的,也就是不要设置UIBarButtonSystemItemFixedSpace这种风格的item
    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;
      }
    }
  }
}

改后效果.png

Demo地址:https://github.com/StoneMover/navDemo.git

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们