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];
       });
    }];
相关推荐
传奇开心果编程11 小时前
【Flutter踩坑排雷】第7课:巨型 build 函数坑|全部 UI 写在同一个 build,维护难、隐性异常
android·flutter·ios·移动开发·跨平台·dart·声明式ui
瓦瓦gogo15 小时前
第一次了解 iOS 开发:从 Swift、SwiftUI 到公共组件
ios·swiftui·swift
全栈探索者17 小时前
从素材到成片:ffmpeg 拼接、转码与字幕,一条流水线交付
macos·ffmpeg·aigc·comfyui·视频剪辑
Liben19 小时前
Weex开发踩坑记录
android·前端·ios
向阳是我19 小时前
Mac 命令行获取 APK 公钥和证书 MD5 指纹
macos
season_zhu21 小时前
Skills For Real Engineers 系列之三:需求聊清楚了,怎么一步步走主流程,做到交付?
ios·ai编程
茶底世界之下1 天前
窗边花瓶太暗?用 Awaking 看提亮室内的代价
ios
2501_915909061 天前
Windows 上用 VS Code 调试 iPhone 真机 App,KXBuild 断点、崩溃定位实操
ide·windows·vscode·ios·iphone·个人开发·敏捷流程
lpfasd1231 天前
Ollama 还是 LM Studio:在 24GB 的 M6 Mac 上,我把 Ollama 卸载了
macos·策略模式
情 九1 天前
MCP 开发环境搭建:Mac 与 Windows 跑通 Python 服务和 stdio 客户端
windows·python·macos·mcp