iOS 导航栏view创建

一. 思路
  • 给ViewController创建一个分类,里面放导航栏view的创建方法
  • 如果需要使用button,button的点击使用block来解决
二. 代码
1. 首先需要一个可以使用block处理点击事件的button,参考这里
2. 然后给ViewController创建一个分类,并在里面实现代码
复制代码
- (UIView *)createNavigationItemTitleViewWithTitle:(NSString *)title{
    UILabel *label = [[UILabel alloc] init];
    label.text = title;
    label.font = ISFont_17;
    label.textColor = [UIColor whiteColor];
    CGSize labelSize = [label.text sizeWithAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont boldSystemFontOfSize:17], NSFontAttributeName, nil]];
    label.frame = CGRectMake(0, 0, labelSize.width, labelSize.height);
    return label;
}

- (UIBarButtonItem *)createLeftBarButtonItemWithImage:(UIImage *)leftBarImage touch:(void(^)(UIButton *button))touchBlock{
    BlockButton * leftButton = [BlockButton buttonWithType:UIButtonTypeCustom];
    leftButton.frame = CGRectMake(0, 0, 20, 20);
    [leftButton setImage:leftBarImage forState:UIControlStateNormal];
    
    [leftButton addTapBlock:^(UIButton *button) {
        touchBlock(button);
    }];
    
    return [[UIBarButtonItem alloc] initWithCustomView:leftButton];
}
3. 在需要的位置调用即可
复制代码
//设置vc标题
self.navigationItem.titleView = [self createNavigationItemTitleViewWithTitle:self.labelInfo.szLabelName];
//设置返回按钮
self.navigationController.interactivePopGestureRecognizer.delegate = (id)self;
    __weak typeof(self) weakSelf = self;
    self.navigationItem.leftBarButtonItem = [self createLeftBarButtonItemWithImage:[UIImage imageNamed:@"backbutton"] touch:^(UIButton *button) {
       dispatch_async(dispatch_get_main_queue(), ^{
           [weakSelf.navigationController popViewControllerAnimated:YES];
       });
    }];
相关推荐
Digitally1 小时前
如何在没有 iTunes 的情况下备份 iPhone
ios·iphone
刘_小_二2 小时前
iOS用Xib 之三等分以及多等分思路
ios
season_zhu3 小时前
Swift:优雅又强大的语法糖——Then库
ios·架构·swift
江梦寻5 小时前
MacOS下Homebrew国内镜像加速指南(2025最新国内镜像加速)
开发语言·后端·python·macos·架构·策略模式
*Lisen5 小时前
重新安装解决mac vscode点击不能跳转问题
ide·vscode·macos
I烟雨云渊T12 小时前
iOS 门店营收表格功能的实现
ios
weixin_3875456412 小时前
如何把 Mac Finder 用得更顺手?——高效文件管理定制指南
macos
itme26816 小时前
解决cocos 2dx/creator2.4在ios18下openURL无法调用的问题
macos·objective-c·cocoa
明月看潮生18 小时前
青少年编程与数学 01-011 系统软件简介 07 iOS操作系统
ios·青少年编程·操作系统·系统软件
90后的晨仔20 小时前
RxSwift 框架解析
前端·ios