2011-04-13 57 views
2

我在Interface Builder中創建了一個UIBarButton項目,並將它鏈接到類中的UIBarButton項目屬性。在Interface Builder中它是Style = Plain and Identifier = Custom and it's Title is blank如何在Interface Builder中設置後以編程方式修改UIBarButtonItem視圖?

viewDidLoad方法中的類文件內我想將自定義視圖添加到此UIBarButtonItem屬性。

E.g

UISegmentedControl *newButton = [[UISegmentedControl alloc] initWithItems:....]; 
newButton.momentary = YES; 
newButton.segmentedControlStyle = UISegmentedControlStyleBar; 
newButton.tintColor = [UIColor .....]; 

[self.myBarButtonItem setCustomView:newButton]; 

,這導致NOTHING顯示出來的。這是爲什麼?

我讀過,如果我編程方式創建的UIBarButtonItem:

UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithCustomView:newButton]; 

然後這個BarButtonItem添加到工具欄 - 這是可行的。我的問題是我有很多東西在我的工具欄上,這個UIBarButton項目需要在工具欄的FAR右側,如果我不能直接在界面生成器中鏈接它,那麼我將不得不構建所有我的工具欄項目編程獲取我需要的佈局。

所以當鏈接到在IB中創建的UIBarButtonItem時,有沒有辦法用customView做到這一點?

謝謝!

+0

我用我喜歡用的方法編輯我的答案,這樣我就不再是這樣一個便宜的混蛋了;) – 2011-04-13 21:46:17

回答

3

要更改UIToolBar上的東西,請使用它的items屬性。這應該回答你的問題:How to programmatically replace UIToolBar items built in IB

編輯:

我喜歡那些工作的方式,是讓一堆IBOutlets的每一個的UIBarButtonItem視圖控制器類。在界面生成器中,我把第一個(默認)項目放在工具欄上,作爲工具欄子視圖和所有這些,其餘的我把它們放在xib中的頂層項目(與連接到視圖的視圖相同視圖控制器的.view屬性出口)。這樣我就不用編程創建它們。並且仍然隱藏它們以便稍後將它們附加到uitolbar。

如果您使用這種方法,請不要忘記在頂級IBOutlets上調用release,如果您使用ivar IBOutlets(而不是@property IBOutlets)作爲xib中未連接到的所有頂級對象KVC編譯器參考。

相關問題