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];
       });
    }];
相关推荐
故事还在继续吗3 小时前
Mac 本地部署大模型
macos·llm·qwen
嵌入式×边缘AI:打怪升级日志4 小时前
转换模块(十二):实现 RGB 转 RGB + 项目整合与上机实验
开发语言·ios·swift
唐诺4 小时前
IOS学习路线计划
ios
for_ever_love__4 小时前
UI学习:无限轮播视图
学习·ui·ios·objective-c
MonkeyKing4 小时前
iOS Block 底层深度解析:结构、变量捕获、copy逻辑与循环引用本质
ios
MonkeyKing4 小时前
iOS ARC 本质:__strong / __weak / __unsafe_unretained / __autoreleasing 深度解析
ios
邵奈一5 小时前
M1 Max Mac版本实测 Rapid-MLX 项目(据说比ollama快4倍)
人工智能·macos·大模型
koping_wu5 小时前
【Claude Code】Mac安装Claude Code、通过阿里云百炼接入Claude Code
macos·阿里云·云计算·ai编程
humors2215 小时前
全平台日常使用的国外应用
android·ios·app·安卓·应用·国外