视觉问题:
我试过把图像放在自己框架的中心,没有运气.我也试图将它与xCGRect一起玩,但没有运气.我认为我可以放一个与导航栏背景相同的空图标; 但是,我不想这样做.我右边可能有2-3个图标; 什么呢?
let image = UIImage(named: "some_logo")!
let imageSize = CGSizeMake(60, 42)
let marginX: CGFloat = (self.navigationController!.navigationBar.frame.size.width / 2) - (imageSize.width / 2)
let imageView = UIImageView(frame: CGRect(x: marginX, y: 0, width: imageSize.width, height: imageSize.height))
imageView.image = image
imageView.contentMode = .ScaleAspectFit
self.navigationItem.titleView = imageView
Run Code Online (Sandbox Code Playgroud)
我更喜欢快速但是obj-c解决方案也受到欢迎.
任何指针赞赏.
这个应用程序与KIA无关,它只是一些我从谷歌搜索中搜索的标识,搜索"一些标识".
Sud*_*135 10
我遇到了同样的问题.然后我尝试了下面显示的一个代码.
override func viewDidAppear(animated: Bool) {
let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 150, height: 40))
imageView.contentMode = .ScaleAspectFit
let image = UIImage(named: "googlePlus")
imageView.image = image
navigationItem.titleView = imageView
}
Run Code Online (Sandbox Code Playgroud)
当我使用左右按钮测试时,此代码工作正常.
但在我以前的代码中没有右键按钮.
所以图像正朝着正确的方向发展.
为了解决这个问题,我创建了一个右栏按钮并将色调颜色更改为清晰的颜色.
所以一切似乎都运转正常.这是您的问题的一个临时解决方案.
小智 7
最简单的方法是在Interface Builder中.
只需从对象库拖动一个'NavigationItem'并将其放入ViewController,然后放置标题所在的UIView(确保将背景设置为'clear')然后将UIImageView放入该视图并在Attributes中设置图像检查员到您需要的图像.相应地缩放UIImage并相应地设置约束.
我使用@idrougge 的提示创建了一个扩展来解决这个问题。
为了使标题视图图像居中,无论您有什么按钮,都将内容视图设置为标题视图,然后将图像视图添加为内容视图的子视图。最后,使用约束,图像视图在其父视图(内容视图)内对齐。
import UIKit
extension UIViewController {
func addLogoToNavigationBarItem() {
let imageView = UIImageView()
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.heightAnchor.constraint(equalToConstant: <your_height>).isActive = true
imageView.contentMode = .scaleAspectFit
imageView.image = <your_image>
//imageView.backgroundColor = .lightGray
// In order to center the title view image no matter what buttons there are, do not set the
// image view as title view, because it doesn't work. If there is only one button, the image
// will not be aligned. Instead, a content view is set as title view, then the image view is
// added as child of the content view. Finally, using constraints the image view is aligned
// inside its parent.
let contentView = UIView()
self.navigationItem.titleView = contentView
self.navigationItem.titleView?.addSubview(imageView)
imageView.centerXAnchor.constraint(equalTo: contentView.centerXAnchor).isActive = true
imageView.centerYAnchor.constraint(equalTo: contentView.centerYAnchor).isActive = true
}
}
Run Code Online (Sandbox Code Playgroud)
我希望这可以帮助别人,
哈维
| 归档时间: |
|
| 查看次数: |
9443 次 |
| 最近记录: |