[英]Iphone/Ipad Add Image and Text to Navigation Title
我只是想在navigationItem標題中添加圖像和文本。 這就是我正在做的,但它只顯示圖像而不是標題。 這似乎很容易。
示例(
self.navigationItem.titleView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"logo_small_white.png"]] autorelease];
self.navigationItem.title = @"Company";
這是我的代碼:
UIView *myView = [[UIView alloc] initWithFrame: CGRectMake(0, 0, 300, 30)];
UILabel *title = [[UILabel alloc] initWithFrame: CGRectMake(40, 0, 300, 30)];
title.text = NSLocalizedString(@"My Title", nil);
[title setTextColor:[UIColor whiteColor]];
[title setFont:[UIFont boldSystemFontOfSize:20.0]];
[title setBackgroundColor:[UIColor clearColor]];
UIImage *image = [UIImage imageNamed:@"MyLogo.png"];
UIImageView *myImageView = [[UIImageView alloc] initWithImage:image];
myImageView.frame = CGRectMake(0, 0, 30, 30);
myImageView.layer.cornerRadius = 5.0;
myImageView.layer.masksToBounds = YES;
myImageView.layer.borderColor = [UIColor lightGrayColor].CGColor;
myImageView.layer.borderWidth = 0.1;
[myView addSubview:title];
[myView setBackgroundColor:[UIColor clearColor]];
[myView addSubview:myImageView];
self.navigationItem.titleView = myView;
通過設置自定義標題視圖,您將替換通常顯示標題文本的標准視圖。 從UINavigationItem
titleView
的文檔:
如果將此屬性設置為自定義標題,則會顯示該屬性而不是標題。
所以,你需要添加自己的觀點(可能是一個UILabel
),以顯示你的標題-這樣做將增加的一種方式UILabel
和UIImageView
上述作為容器的子視圖UIView
,並設置為titleView
。
在Swift 2中:
var myView: UIView = UIView(frame: CGRectMake(0, 0, 300, 30))
var title: UILabel = UILabel(frame: CGRectMake(40, 0, 300, 30))
title.text = "The Title"
title.textColor = UIColor.blackColor()
title.font = UIFont.boldSystemFontOfSize(20.0)
title.backgroundColor = UIColor.clearColor()
var image: UIImage = UIImage(named: "your-image")!
var myImageView: UIImageView = UIImageView(image: image)
myImageView.frame = CGRectMake(0, 0, 30, 30)
myImageView.layer.cornerRadius = 5.0
myImageView.layer.masksToBounds = true
myImageView.layer.borderColor = UIColor.lightGrayColor().CGColor
myImageView.layer.borderWidth = 0.1
myView.addSubview(title)
myView.backgroundColor = UIColor.clearColor()
myView.addSubview(myImageView)
self.navigationItem.titleView = myView
相關問題:titleView會自動居中,如果上述示例不是這種情況,那么您可能會使用較小的屏幕尺寸(例如iPhone)。 只需將UIView和UILabel的寬度從300改為更小即可。 當有空間時它會重新回到中心。
UIImage *image = [UIImage imageNamed:@"image.png"]; // Image name with extension
self.navigationItem.titleView = [[[UIImageView alloc] initWithImage:image] autorelease];
這可能是最短的方式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.