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];
       });
    }];
相关推荐
_瑞18 小时前
深入理解灵动岛
前端·ios·app
星野爱89520 小时前
崩坏星穹铁道4.4版本即将前瞻!Mac畅玩PC端开荒新版本
macos
黑科技iOS上架20 小时前
分享一个开源的iOS应用AppIcon生成器
经验分享·ios
funnycoffee12321 小时前
lacp报文占多少字节?报文的目的mac
网络·网络协议·macos
itwangyang5201 天前
Claude Code macOS 安装完整指南:Homebrew、原生脚本与常见问题解决
macos
汤姆yu2 天前
macOS系统下Aider完整安装、配置与实战使用教程
大数据·人工智能·算法·macos·github·copilot
wabil2 天前
【LVGL】滑动切换页面的界面优化实践
开发语言·ios·swift
威武的花瓣2 天前
调用Page.RegisterAsyncTask()的异步页
ios·iphone
码云数智-园园2 天前
SwiftUI 6 生产落地踩坑实录
macos·objective-c·cocoa
向阳是我2 天前
在 Mac(M2)上用 faster-whisper 实现高精度中文语音转文字
python·macos·ai·whisper·语音识别