【问题标题】:Adding UIBarButtonItem's to a UIToolbar将 UIBarButtonItem 添加到 UIToolbar
【发布时间】:2013-03-06 11:17:44
【问题描述】:

我需要向 UINavigationController 的 UIToolbar 添加按钮,这也是我的根。我希望 UIToolbar 在显示特定 UIViewController 时出现。因此,我将这段代码放在了 UIViewController 子类的 viewDidLoad 方法中:

UIBarButtonItem* item = [[UIBarButtonItem alloc] initWithTitle:@"Title" style:UIBarButtonItemStyleBordered target:self action:@selector(doSomething)];
item.width = 300;
item.tintColor = [UIColor whiteColor];
UIBarButtonItem* item2 = [[UIBarButtonItem alloc] initWithTitle:@"Title2" style:UIBarButtonItemStyleBordered target:self action:@selector(doSomething)];

NSMutableArray* theItems = [self.navigationController.toolbar.items mutableCopy];
[theItems addObject:item];
[theItems addObject:item2];
[self.navigationController.toolbar setBarStyle:UIBarStyleBlackOpaque];
[self.navigationController setToolbarHidden:NO animated:YES];
[self.navigationController setToolbarItems:theItems animated:NO];
//self.navigationController.toolbarItems = theItems; // Tried both

UILabel* label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 20)];
label.text = @"kjhdkjhadsda";
[self.navigationController.toolbar addSubview:label];

这仅显示 UILabel 在正确的位置,没有其他内容出现。 UILabel 对我来说没用,它只是一个测试。我还尝试分配一个新数组,而不是从组件中复制一个。忽略缺少的版本,这只是测试代码。

我阅读了很多关于此的问题,但似乎没有任何答案有助于使其发挥作用。知道这段代码有什么问题吗?

【问题讨论】:

    标签: objective-c ios5 uitoolbar uitoolbaritem


    【解决方案1】:

    似乎您正在尝试在行中制作 nil 的可变副本

    [self.navigationController.toolbar.items mutableCopy];
    

    默认方法 navigationController.toolbar.items 没有项目并返回 nil

    更新

    方法 - (void)setToolbarItems:(NSArray*)toolbarItems animated:(BOOL)animated 如果将其发送到 UINavigationController,则不会执行任何操作。您需要将工具栏项设置为由导航控制器管理的控制器。此行将使您的按钮可见:

    [self setToolbarItems:theItems animated:NO];
    

    【讨论】:

    • 我指定我也尝试分配一个新的。也许不清楚我指的是那个,抱歉。
    • 您是否检查过您的 self.navigationController != nil。您的代码看起来不错,应该可以工作。并尝试通过 UIViewController 的方法 [self setToolbarItems:theItems animated:NO]; 设置工具栏项
    • Il self.navigationController 为 nil 我不希望显示工具栏并正确添加标签,对吧?我刚刚尝试了 UIViewController 中的 setToolbarItems 方法,也不知道它存在,但没有出现任何按钮。还有什么想法吗?也许代码没问题,但可能有其他东西阻止按钮显示?
    • 看来你没有正确理解我的意思。我试图说 self.navigationController 在此方法中可能为零,然后可以稍后访问。请检查这个。顺便说一句,您在哪个时刻尝试访问 navigationController(在 loadView、viewDidLoad 或 viewDidAppear 中)?
    • viewDidLoad 这是我操作工具栏的唯一方法。所以我显示它,它被显示,我添加按钮,那些没有显示,我放置标签,它被显示。检查 nil self.navigationController 并且它不是 nil。
    猜你喜欢
    • 1970-01-01
    • 2011-12-01
    • 2011-10-21
    • 2010-09-24
    • 1970-01-01
    • 2016-11-24
    • 1970-01-01
    • 2011-06-18
    • 1970-01-01
    相关资源
    最近更新 更多