2014-05-11 32 views
0

我知道它看起來很簡單,並且已經被問了很多次,但是我無法讓它工作。我想在我的工具欄中添加兩個按鈕。一個在右側,另一個在左側。這裏是代碼,但是應該顯示在右側的靈活代碼根本沒有出現。以下是代碼:現在顯示在UIToolbar上的彈性欄按鈕項目

toolbar = [[UIToolbar alloc] init]; 
toolbar.frame = CGRectMake(0, 0, self.view.frame.size.width, 44); 
NSMutableArray *items = [[NSMutableArray alloc] init]; 

[items addObject:[[UIBarButtonItem alloc] initWithTitle:@"next" style:UIBarButtonItemStylePlain target:self action:@selector(nextResult:)]]; 

UIBarButtonItem *done=[[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:self action:@selector(showSearch:)]; 
[done setImage:[UIImage imageNamed:@"cancel"]]; 
[items addObject:done]; 

[toolbar setItems:items animated:NO]; 

回答

2

您需要使用UIBarButtonSystemItemFlexibleSpace代替UIBarButtonSystemItemFixedSpace

代碼:

toolbar = [[UIToolbar alloc] init]; 
toolbar.frame = CGRectMake(0, 0, self.view.frame.size.width, 44); 
NSMutableArray *items = [[NSMutableArray alloc] init]; 

[items addObject:[[UIBarButtonItem alloc] initWithTitle:@"next" style:UIBarButtonItemStylePlain target:self action:@selector(nextResult:)]]; 

UIBarButtonItem *space = [[UIBarButtonItem alloc]initWithBarButtonSystemItem: UIBarButtonSystemItemFlexibleSpace target:nil action:nil]; 
[items addObject:space]; 

[items addObject:[[UIBarButtonItem alloc] initWithTitle:@"cancel" style:UIBarButtonItemStylePlain target:self action:@selector(showSearch:)]]; 

[toolbar setItems:items animated:NO]; 

參考:UIBarButtonItem Class Reference

+1

完成按鈕是一個空間。因此它不會出現。 – dasdom

+1

@dasdom:是的,糾正了這一點。我在添加評論時正在進行編輯。無論如何感謝 –

+0

感謝你midhun! – devdev101

1

系統項目UIBarButtonSystemItemFixedSpace的項目是一個空格,而不是按鈕對象。因此它顯示出來。這只是沒有按鈕。

更改您的代碼

toolbar = [[UIToolbar alloc] init]; 
toolbar.frame = CGRectMake(0, 0, self.view.frame.size.width, 44); 
NSMutableArray *items = [[NSMutableArray alloc] init]; 

[items addObject:[[UIBarButtonItem alloc] initWithTitle:@"next" style:UIBarButtonItemStylePlain target:self action:@selector(nextResult:)]]; 

UIBarButtonItem *space = [[UIBarButtonItem alloc]initWithBarButtonSystemItem: UIBarButtonSystemItemFlexibleSpace target:nil action:nil]; 
[items addObject:space]; 

[items addObject:[[UIBarButtonItem alloc] initWithTitle:@"cancel" style:UIBarButtonItemStylePlain target:self action:@selector(showSearch:)]]; 

[toolbar setItems:items animated:NO]; 
+0

他們仍然顯示彼此相鄰在工具欄的左側! – devdev101

+1

將空間的類型更改爲「UIBarButtonSystemItemFlexibleSpace」。 – dasdom

+0

它應該是靈活的空間而不是固定的空間!無論如何感謝 – devdev101