2011-12-12 73 views
2

我想通过工具栏的帮助来定制我的NavigationBar。 我如下编程来实现它:UIToolbar精确尺寸

UIToolbar* tools = [[UIToolbar alloc] initWithFrame: CGRectMake(0, 0, 100, 44.01)]; 

,然后我把它添加到我的导航栏。问题是,我对这个边界丑的效果:

navigationbar + toolbar

我试图改变y和高度值,但没有任何结果。 你有什么想法可以避免这种情况吗?

在此先感谢,yassa

+1

您正在添加一个工具栏到导航栏? – Till

+0

是的,我在一些教程中发现了这种方法......这是一种错误的方法吗? – yassassin

+1

是的,看到shannogans的答案 - 这是“正确的”方式 – Till

回答

2

我部分同意以前的答案和评论。 您建议的解决方案适用于自定义按钮。但是如果我想实现标准的编辑按钮呢? 访问标准按钮/图标是通过UIBarButtonItem类,而不是UIButton。而且你不能将UIBarButtonItem对象添加到UIView。

在网络上进行了很多研究之后,我发现了完全覆盖我的需求的解决方案。工具栏必须按以下方式创建:

UIToolbar *tools = [[UIToolbar alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 95.0f, 44.01f)]; 
tools.tintColor = self.navigationController.navigationBar.tintColor; 
tools.barStyle = -1; 

这是结果:

my toolbar

希望它能帮助! yassa

2

我不会这样做。 您可以通过向navigationItem.rightBarButtonItem添加带有2个按钮的视图来实现相同的效果。它很简单:

// view that will hold the buttons 
UIView* container = [[UIView alloc] init]; 

// create 1 button and add it to the container 
UIButton* button = [[UIButton alloc] init........]; 
[container addSubview:button]; 


//create 2 button and add it to the container 
button = [[UIButton alloc] init.........]; 
[container addSubview:button]; 


// now create a Bar button item 
UIBarButtonItem* barButtonItem = [[UIBarButtonItem alloc] initWithCustomView:container]; 

// set the nav bar's right button item 
self.navigationItem.rightBarButtonItem = barButtonItem; 
+0

+1正确可靠的处理方式 – Till

0

或者你可以这样做。 只需创建UIToolbar的新的子类这样

@interface MyToolbar : UIToolbar 

    @end 

    @implementation MyToolbar 

    - (id)initWithFrame:(CGRect)frame { 

     if ((self = [super initWithFrame:frame])) { 

      self.opaque = NO; 
      self.backgroundColor = [UIColor clearColor]; 
      self.clearsContextBeforeDrawing = YES;  
     } 
     return self; 
    } 


    - (void)drawRect:(CGRect)rect { 
     // do nothing 
    } 

    - (void)dealloc { 
     [super dealloc]; 
    } 

@end 

而且使用它作为正常UIToolbar。我不知道为什么,但它只是起作用。