找回密码
 会员注册
查看: 21|回复: 0

知识点:iOS调整导航栏按钮与边框的距离

[复制链接]

2万

主题

0

回帖

6万

积分

超级版主

积分
64116
发表于 2024-10-12 09:28:42 | 显示全部楼层 |阅读模式
废话少说,直接上干货!1. 一个设置按钮相对于navBar约束的类.h文件#import typedef NS_ENUM(NSInteger, MANavBarBtnPosition) { MANavBarBtn_Left, MANavBarBtn_Right};NS_ASSUME_NONNULL_BEGIN@interface MANavBarBtnView : UIView@property (nonatomic, assign) MANavBarBtnPosition position;+ (void)setupNavBarBtnWithNavItemUINavigationItem *)navItem viewUIView *)view positionMANavBarBtnPosition)position;@endNS_ASSUME_NONNULL_END.m 文件#import "MANavBarBtnView.h"#define Margin 10.0@interface MANavBarBtnView () { BOOL applied;}@end@implementation MANavBarBtnView- (void)layoutSubviews { [super layoutSubviews]; if (applied || [[[UIDevice currentDevice] systemVersion] doubleValue] = 11.0) { MANavBarBtnView *barBtnView = [[MANavBarBtnView alloc] initWithFrame:view.frame]; [barBtnView setPosition:position]; [barBtnView addSubview:view]; UIBarButtonItem *btnItem = [[UIBarButtonItem alloc] initWithCustomView:barBtnView]; if (position == MANavBarBtn_Left) { [navItem setLeftBarButtonItem:btnItem]; } else { [navItem setRightBarButtonItem:btnItem]; } } else { UIBarButtonItem *space = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:NULL]; [space setWidth:-Margin]; NSArray *items = @[space, [[UIBarButtonItem alloc] initWithCustomView:view]]; if (position == MANavBarBtn_Left) { [navItem setLeftBarButtonItems:items]; } else { [navItem setRightBarButtonItems:items]; } }}@end2. 使用过程在有导航栏的Controller中,按如下方式调用即可,如设置左侧返回按钮:- (void)viewWillAppearBOOL)animated { [super viewWillAppear:animated]; [self setupBackItem];}// 设置返回按钮- (void)setupBackItem { if (self.navigationController.topViewController & self.navigationController.viewControllers.firstObject != self) { [MANavBarBtnView setupNavBarBtnWithNavItem:self.navigationItem view:[self backButton] position:MANavBarBtn_Left]; }}- (UIButton *)backButton { UIImage *normalImage = [[UIImage kk_imageNamed"ma_icon_back"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate]; UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom]; [backButton setImage:normalImage forState:UIControlStateNormal]; backButton.frame = CGRectMake(.0, .0, 35.0, 40.0); backButton.imageEdgeInsets = UIEdgeInsetsMake(.0, -8.0, .0, 8.0); backButton.tintColor = [self.page.window.navigationBarTextStyle isEqualToString"white"] [UIColor whiteColor]: [UIColor blackColor]; [backButton addTarget:self actionselector(backButtonClicked forControlEvents:UIControlEventTouchUpInside]; return backButton;}使用过程中,请注意 MANavBarBtnView 与初始化 navigationItem 时的 customView 之间的区别。
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 会员注册

本版积分规则

QQ|手机版|心飞设计-版权所有:微度网络信息技术服务中心 ( 鲁ICP备17032091号-12 )|网站地图

GMT+8, 2024-12-26 12:51 , Processed in 2.235054 second(s), 25 queries .

Powered by Discuz! X3.5

© 2001-2024 Discuz! Team.

快速回复 返回顶部 返回列表