因此,我嘗試使用以下代碼在 UINavigationbar 的 titleview 屬性中添加 UIImageview。問題是,盡管我將特定大小設定為包含 UIImageview 的 UIView 包含影像,但它無法按預期作業。結果是導航欄中的影像比我使用 CGRectMake 設定的影像更大。此外,在某些視圖中,它與中心不對齊!我錯過了什么?還有另一種方法可以將影像添加到導航欄嗎?
-(void)viewDidLayoutSubviews{
UIView *containerView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f,10.0f,16.0f)];
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0.0f, 0.0f,10.0f,16.0f)];
CGSize imageSize = CGSizeMake(10, 16);
CGFloat marginX = (self.navigationController.navigationBar.frame.size.width / 2) - (imageSize.width / 2);
imageView.frame = CGRectMake(marginX, 11, imageSize.width, imageSize.height);
imageView.contentMode = UIViewContentModeScaleAspectFit;
UIImage *image = [UIImage sdk_imageName:@"logo.png"];
[imageView setImage:image];
[containerView addSubview:imageView];
self.navigationItem.titleView=imageView;
}
uj5u.com熱心網友回復:
我查看了您的代碼,發現了一些框架問題,并且在底部您沒有在 titleview 中傳遞容器視圖,這不會按預期呈現視圖。
請試試這個。
UIView *containerView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f,self.navigationController.navigationBar.frame.size.width,self.navigationController.navigationBar.frame.size.height)];
UIImageView *imageView = [[UIImageView alloc] init];
//containerView.backgroundColor = [UIColor redColor];
CGSize imageSize = CGSizeMake(60, self.navigationController.navigationBar.frame.size.height);
CGFloat marginX = (self.navigationController.navigationBar.frame.size.width / 2) - (imageSize.width / 2);
imageView.frame = CGRectMake(marginX, 0, imageSize.width, imageSize.height);
imageView.contentMode = UIViewContentModeScaleAspectFit;
UIImage *image = [UIImage imageNamed: @"2.jpg"];
[imageView setImage:image];
[containerView addSubview:imageView];
self.navigationItem.titleView=containerView;
結果:

uj5u.com熱心網友回復:
更簡單的方法......對影像視圖大小使用自動布局約束......居中是自動處理的。
10x16影像視圖為titleView:
UIImage *img = [UIImage imageNamed:@"logo"];
UIImageView *titleImageView = [[UIImageView alloc] initWithImage:img];
titleImageView.contentMode = UIViewContentModeScaleAspectFit;
titleImageView.translatesAutoresizingMaskIntoConstraints = NO;
[NSLayoutConstraint activateConstraints:@[
[titleImageView.widthAnchor constraintEqualToConstant:10.0],
[titleImageView.heightAnchor constraintEqualToConstant:16.0],
]];
self.navigationItem.titleView = titleImageView;
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/372641.html
上一篇:如何從ArdalisCleanArchitecture中的遷移中忽略域事件?
下一篇:聯合的交集用作度量或損失
