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];
       });
    }];
相关推荐
懋学的前端攻城狮24 分钟前
第三方SDK集成沉思录:在便捷与可控间寻找平衡
ios·前端框架
冰凌时空3 小时前
Swift vs Objective-C:语言设计哲学的全面对比
ios·openai
花间相见4 小时前
【大模型微调与部署03】—— ms-swift-3.12 命令行参数(训练、推理、对齐、量化、部署全参数)
开发语言·ios·swift
SameX5 小时前
删掉ML推荐、砍掉五时段分析——做专注App时我三次推翻自己,换来了什么
ios
爱吃香蕉的阿豪5 小时前
Mac 远程操作 Windows 开发:ZeroTier + JetBrains 实战指南
windows·macos·zerotoer
YJlio6 小时前
2026年4月19日60秒读懂世界:从学位扩容到人形机器人夺冠,今天最值得关注的6个信号
python·安全·ios·机器人·word·iphone·7-zip
90后的晨仔19 小时前
《SwiftUI 高级特性第1章:自定义视图》
ios
空中海19 小时前
第二章:SwiftUI 视图基础
ios·swiftui·swift
大嘴皮猴儿20 小时前
从零开始学商品图翻译:小白也能快速掌握的多语言文字处理与上架技巧
大数据·ide·人工智能·macos·新媒体运营·xcode·自动翻译
空中海1 天前
第七章:iOS网络与数据持久化
网络·ios