2013-11-26 62 views
2

我想爲我的應用中的導航欄使用自定義titleView,以便它可以是用戶可編輯的。我試圖得到默認的字體/對齊/等,所以我可以將它應用到我的新視圖,所以它看起來像一個正常的導航欄標題。獲取UINavigationBar的默認titleTextAttributes

我使用

NSMutableDictionary *myDict = [[NSMutableDictionary alloc] initWithDictionary:self.navigationController.navigationBar.titleTextAttributes]; 
NSLog(@"%@", myDict); 

但這只是顯示一個空的字典。我已經看過其他答案,這表明這應該返回默認字體。

我做錯了什麼?或者在iOS7中改變了?

編輯:由於以下卡格拉,我已經更新了我的代碼:

// Get the default title label 
UILabel *navigationTitleLabel; 
for (UIView *sv in self.navigationController.navigationBar.subviews) 
{ 
    if (sv.subviews.count > 0 && [sv.subviews[0] isKindOfClass:[UILabel class]]) 
    { 
     navigationTitleLabel = (UILabel *)sv.subviews[0]; 
     break; 
    } 
} 

// Set the new text field to have the same attributes as the default title label 
textField.font = navigationTitleLabel.font; 
textField.textColor = navigationTitleLabel.textColor; 
textField.textAlignment = NSTextAlignmentCenter; 
self.navigationItem.titleView = textField; 

回答

1

您可以訪問導航欄的子視圖,因爲UINavigationBarUIView子類。 這是iOS 7的版本。在舊版本中,子視圖的順序可能與此不同。然而,想法是一樣的,請翻閱UINavigationBar的子視圖並達到標題。

for (UIView *sv in self.navigationController.navigationBar.subviews) 
{ 
    if (sv.subviews.count > 0 && [sv.subviews[0] isKindOfClass:[UILabel class]]) 
    { 
     self.navigationTitleLabel = (UILabel *)sv.subviews[0]; 
     break; 
    } 
} 
+0

非常感謝您的幫助。我用你的代碼在導航欄中找到UILabel,然後直接從那裏獲取字體屬性,並將它們放在我的新視圖(這是一個UITextField)。 – Frakur