gpt4 book ai didi

iphone - 向NavigationBar的titleview添加按钮,无需重复代码

转载 作者:行者123 更新时间:2023-12-03 19:56:16 28 4
gpt4 key购买 nike

为了提供一些背景信息,我正在制作一个基于 UINavigationControlled 的博客类型应用程序(我认为它最类似于 iPhone 的 facebook 应用程序)。无论当前处于事件状态的 View 如何,导航栏都会在其标题区域中显示一些按钮,例如“好友请求”和“事件通知”。与 Facebook 应用程序大致相同,单击这些按钮将创建一个弹出 View 。

目前,我正在以一种我认为效率极低的方式做事。对于加载的每个 View ,我都会重新创建按钮并将它们添加到导航栏。我的代码如下:

//Setup the custom middle buttons
UIView *container = [[UIView alloc] init];
container.frame = CGRectMake(0, 0, 80, 44);

// create a button and add it to the container
UIButton *notificationButton = [UIButton buttonWithType:UIButtonTypeCustom];
notificationButton.frame = CGRectMake(0, 0, 35, 44);
[notificationButton addTarget:self
action:@selector(showNotifications:)
forControlEvents:UIControlEventTouchUpInside];
[container addSubview:notificationButton];


// add another button to the container
UIButton *friendActivityButton = [UIButton buttonWithType:UIButtonTypeCustom];
friendActivityButton.frame = CGRectMake(45, 0, 35, 44);
[friendActivityButton addTarget:self
action:@selector(showFriendActivity:)
forControlEvents:UIControlEventTouchUpInside];
[container addSubview:friendActivityButton];

// Set the titleView to the container view
[self.navigationItem setTitleView:container];
[container release];

由于我的应用程序有多个 View 并且导航栏始终可见,因此继续重新创建按钮,将它们添加到容器 View ,然后将该 View 添加到导航 Controller 的 titleView 似乎很愚蠢。

达到相同效果的更好方法是什么?我正在研究子类化或为 UINavigationBar 创建一个类别,并可能在其中添加容器 View 代码。但是,我不知道如何使选择器在这些情况下工作。我也不确定如何使用 UINavigationBar 类别访问 titleView 属性。

对此的任何帮助都会很棒!谢谢!

最佳答案

我建议将上述代码放入 UIViewController 类别中(如果您可以从单个根对所有 View Controller 进行子类化,则将其放入 UIViewController 子类中)。然后在 viewDidAppear 中,只需调用上面的代码(或将其放在父类(super class)的 viewDidAppear 中)。我认为子类化 UINavigationBar 会带来更多麻烦,而不是其值(value)。

如果您确实想避免重新创建按钮(可能没有理由这样做,但如果出于某种原因这对您很重要),您可以将按钮连接到某个单例对象,而不是将它们指向 self。单例可以直接处理响应,将消息转发到事件 View Controller ,或者发布事件 View Controller 可以监听的通知。

关于iphone - 向NavigationBar的titleview添加按钮,无需重复代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10004525/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com