【问题标题】:customView on left button of UINavigationBarUINavigationBar 左侧按钮上的 customView
【发布时间】:2010-03-05 10:49:43
【问题描述】:

我正在尝试使用自定义控件实现 UINavigationBar。因此,我在 UINavigationBar 的左侧添加了 UIView,并尝试使用以下代码向该 UIView 添加控件:

UIView *view = navigationController.navigationItem.leftBarButtonItem.customView;
UIButton *button = [[UIButton alloc] initWithFrame:view.frame];
[button setTitle:@"TEST" forState:UIControlStateNormal];
[view addSubview:button];
[button sizeToFit];
[button release];

代码有效,但按钮不出现。

任何帮助将不胜感激。 谢谢。

UPD

好的,我尝试了下面的代码并做了这样的事情:

UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 40, 50)];
[button setTitle:@"XXX" forState:UIControlStateNormal];
UIBarButtonItem *customItem = [[UIBarButtonItem alloc] initWithCustomView:button];
navigationController.visibleViewController.navigationItem.leftBarButtonItem = customItem;
[customItem release];
[button release];

“XXX”标题确实出现了,但它看起来像简单的标签,而不是按钮。有什么想法吗?

【问题讨论】:

    标签: iphone uinavigationbar uinavigationitem


    【解决方案1】:

    是的,您的 UIButton 没有任何阴影。我所做的是使用 UISegmentedControl 免费获得阴影:

    // Add the Menu button to the navigation bar
    NSString* menuLabel = "ShadeButton";
    CGSize textSize = [menuLabel sizeWithFont:[UIFont systemFontOfSize:15.0]];
    UISegmentedControl* menuSegmentedButton = [[UISegmentedControl alloc]
        initWithFrame:CGRectMake(0.0f, 0.0f, textSize.width, 29.0f)];
    menuSegmentedButton.momentary = YES;
    menuSegmentedButton.selected = NO;
    menuSegmentedButton.segmentedControlStyle = UISegmentedControlStyleBar;
    [menuSegmentedButton insertSegmentWithTitle:menuLabel atIndex:0
                                  animated:NO];
    [menuSegmentedButton addTarget:self action:@selector(doMenu)
             forControlEvents:UIControlEventValueChanged];
    UIBarButtonItem* barButton = [[UIBarButtonItem alloc] 
        initWithCustomView:menuSegmentedButton];
    [menuSegmentedButton release];
    self.navigationItem.rightBarButtonItem = barButton;
    

    使用如上所示的 UISegmentedControl 而不是 UIButton 创建您的 UIBarButtonItem,您应该会得到您想要的效果。另一种方法是在按钮上做更多的工作并自己为其创建纹理/自定义图像。

    【讨论】:

    • 好的,我会在最近的一周内试一试,如果成功 - 我会给你赏金:)
    • 按钮的外观似乎与标准样式不同,但对我来说没关系 - 它应该被蒙皮。感谢您的帮助。
    【解决方案2】:

    注意很对。

    如果你只是想要一个不同的标题:

    UIBarButtonItem *customItem = [[UIBarButtonItem alloc] initWithTitle:@"TEST" style:UIBarButtonItemStylePlain target:nil action:nil];
    navigationController.navigationItem.leftBarButtonItem = customItem;
    [customItem release];
    

    如果你真的想要自定义视图:

    // Create Custom View called myView.
    UIBarButtonItem *customItem = [[UIBarButtonItem alloc] initWithCustomView:myView];
    navigationController.navigationItem.leftBarButtonItem = customItem;
    [customItem release];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多