2011-03-01 86 views
2

我需要更改我的UIBarButtonItem標題的字體。目前它是,barbuttonItem.customView = customLabel。現在我希望添加一個選擇器和目標,以便我可以獲取touchDown事件。具有相同的字體樣式。自定義字體到UIbarbuttonItem標題

在此先感謝,

回答

4

您應該只使用UIButton作爲您的自定義視圖。

UIButton *customButton = [UIButton buttonWithType:UIButtonTypeCustom]; 
customButton.titleLabel.font = [UIFont systemFontOfSize:14.0]; 
[customButton setImage:[UIImage imageNamed:@"image_up_state.png"] forState:UIControlStateNormal]; 
[customButton setImage: [UIImage imageNamed:@"image_down_state.png"] forState:UIControlStateHighlighted]; 
[customButton addTarget:self action:@selector(doSomething) forControlEvents:UIControlEventTouchUpInside]; 

這將設置您的自定義字體,然後讓您有一個up狀態圖像和down狀態圖像。當你點擊按鈕時,它會調用doSomething消息。

6

如果您不想創建自定義視圖,則可以使用UIBarItem上的setTitleTextAttributes方法來設置字體。例如,這裏是一個UIBarButtonItem使用它來操縱字體:

[self.filterButton setTitleTextAttributes: 
[NSDictionary dictionaryWithObjectsAndKeys: 
    [UIFont fontWithName:@"Helvetica Neue" size:15.0],UITextAttributeFont, 
    nil]forState:UIControlStateNormal]; 
+1

完美的解決方案!我想知道爲什麼沒有人投票。 – 2013-04-19 12:19:57

+0

我不確定你,但它不適用於我自定義字體(這正是OP所要求的)。 – 2013-11-18 18:38:01

+0

請確保使用NSFontAttributeName指定字體,使用像這樣的字典 - 文字 - 語法: [barButtonItem setTitleTextAttributes:@ {NSFontAttributeName:[UIFont fontWithName:@「AvenirNext-Regular」size:15.0]} forState:UIControlStateNormal] ; – 2014-02-03 14:39:31