2016-02-13 179 views
0

我在導航欄中添加了自定義的標題視圖。導航欄的標題視圖重疊

在每次屏幕更改時,我都會添加另一個標題視圖。

問題是前一個沒有被刪除,我可以一次查看所有視圖。

這裏是我的代碼:

UILabel *lblTitle = [[UILabel alloc] init]; 
lblTitle.text = text; 
CGSize lblSize = [Utility sizeOfText:text withFont:kCGFontMedium(19)]; 
lblTitle.frame = CGRectMake(60, 9, lblSize.width, lblSize.height); 
lblTitle.font =kCGFontMedium(19); 
lblTitle.backgroundColor = [UIColor clearColor]; 
lblTitle.textColor = [UIColor whiteColor]; 
[lblTitle sizeToFit]; 

    [self.navigationController.navigationBar addSubview:lblTitle]; 

我的問題: 註冊並登錄,重疊 enter image description here

+1

的問題是每次添加新的子視圖,而不是替換原有的子視圖。嘗試將舊子視圖設置爲零,或者使用新子視圖重新分配舊子視圖。 – RPK

+0

@RPK如何更換舊的Subivew..Means如何在新的屏幕中獲取Old Subview的引用 – Dalvik

+1

當您在UINavigationController中推送並彈出視圖控制器時,視圖控制器可能會更改,但導航控制器保持不變。您可以嘗試對UINavigationController進行子分類並保留對導航欄子視圖的類引用。然後,您可以在viewDidLoad中添加子視圖一次,然後在需要時更改它。 – RPK

回答

2

解決方案1:每次你要刪除自定義的UIView對象時添加到導航欄

[self.navigationController.navigationBar.subviews enumerateObjectsWithOptions:0 usingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) { 

    if ([obj isMemberOfClass:[UILabel class]]) { 

     [obj removeFromSuperview]; 

    } 

}]; 

UILabel *lblTitle = [UILabel new]; 
lblTitle.text = text; 
CGSize lblSize = [Utility sizeOfText:text withFont:kCGFontMedium(19)]; 
lblTitle.frame = CGRectMake(60, 9, lblSize.width, lblSize.height); 
lblTitle.font = kCGFontMedium(19); 
lblTitle.backgroundColor = [UIColor clearColor]; 
lblTitle.textColor = [UIColor whiteColor]; 
[lblTitle sizeToFit]; 
[self.navigationController.navigationBar addSubview:lblTitle]; 

解決方案2:在類接口中添加屬性以存儲對自定義子視圖的訪問EW中的導航欄

@property (weak, readwrite, nonatomic) UILabel *navSubView; 

[self.lblTitle removeFromSuperview]; 
self.lblTitle = [UILabel new]; 
lblTitle.text = text; 
CGSize lblSize = [Utility sizeOfText:text withFont:kCGFontMedium(19)]; 
lblTitle.frame = CGRectMake(60, 9, lblSize.width, lblSize.height); 
lblTitle.font = kCGFontMedium(19); 
lblTitle.backgroundColor = [UIColor clearColor]; 
lblTitle.textColor = [UIColor whiteColor]; 
[lblTitle sizeToFit]; 
[self.navigationController.navigationBar addSubview:lblTitle]; 
+0

謝謝它正在按預期工作..但我有一個疑問..假設我有六個屏幕,然後在所有六個屏幕上我必須寫這個代碼? – Dalvik

0

或者你可以只使用NavigationItem的 「titleview的」 屬性

的UILabel * titleLabel = [[的UILabel的alloc]初始化]。你可以使用下面的代碼來實現這個功能:* titleView = [[UIView alloc] initWithFrame:titleLabel.frame]; [titleView addSubview:titleLabel];

self.navigationItem.titleView = titleView;

這將確保只有一個標題標籤的實例存在,它不會重疊self.title要麼