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 小时前
强制升级 Xcode 后,一个 10 年老项目有哪些改动点
ios
茶底世界之下1 天前
海边书店的阴天:用 Awaking 留住青绿与暖灯
ios·app·产品
布莱克6052 天前
Swift 类详解:从定义、继承到内存管理的完整指南
服务器·开发语言·ios·ssh·swift·类
布莱克6052 天前
Swift 方法详解:实例方法、类型方法与 mutating 机制
服务器·开发语言·ios·ssh·swift·方法
RobinDevNotes2 天前
24GB Mac 做数字人:声音放本地,画面租云端
人工智能·python·macos·开发工具
茶底世界之下2 天前
旧电影院的红座椅:用 Awaking 留住放映前的光
ios·app·产品
茶底世界之下3 天前
洗衣房的午后斜光:用 Awaking 把光和影分开
ios·app·产品
我是谁的程序员4 天前
iOS 性能分析在 Windows 上怎么做,用 KXBuild 的 kxdevice 替代 Instruments
后端·ios
开心就好20254 天前
通配符 Bundle ID 和精确 Bundle ID 怎么选,推送、iCloud 能不能用通配符
后端·ios
布莱克6054 天前
Swift 枚举详解:从基础语法到关联值与模式匹配
开发语言·ios·swift·枚举