UIImageView无法在Navbar和状态栏中正确定位

时间:2016-10-19 19:43:43

标签: ios swift uiimageview navigation frame

我正在尝试在导航栏中使用图像。继续靠近,但没有雪茄。使用下面的代码,它可以很好地加载图像并使其几乎正确。它看起来在视图周围有一个垫,但我没有约束它。当我删除状态栏时,它会收缩图像,但在导航栏中将其定位好。

    let nav = self.navigationController?.navigationBar

    for parent in self.navigationController!.navigationBar.subviews {
        for childView in parent.subviews {
            if(childView is UIImageView) {
                childView.removeFromSuperview()
            }
        }
    }

    nav?.barStyle = UIBarStyle.Default
    nav?.tintColor = UIColor.blueColor()

    let app = UIApplication.sharedApplication()
    let SBheight = app.statusBarFrame.size.height
    let totalheight = SBheight + nav!.frame.height
    let totalwidth = nav!.frame.width
    let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: totalwidth , height: totalheight))
    imageView.clipsToBounds = true
    imageView.contentMode = .ScaleAspectFill

    var image = UIImage(named: "HRC")
    imageView.image = image

    navigationItem.titleView = imageView

以下是NavBar区域的镜头:

Nav Image Not Placing Correctly.

1 个答案:

答案 0 :(得分:0)

我可以设置导航栏的背景图片,但下面的代码没有问题。

Swift 3.0

let backgroundImage = UIImage(named: "name_of_background_image")?.resizableImage(withCapInsets: UIEdgeInsetsMake(0, 0, 0, 0), resizingMode: .stretch)
self.navigationController?.navigationBar.setBackgroundImage(backgroundImage, for: .default)

Swift 2.3

let backgroundImage = UIImage(named: "name_of_background_image")?.resizableImageWithCapInsets(UIEdgeInsetsMake(0, 0, 0, 0), resizingMode: .Stretch)
self.navigationController?.navigationBar.setBackgroundImage(backgroundImage, forBarMetrics: .Default)

您可以将上面的代码添加到viewDidLoad,并为每个viewController自定义背景图片。

确保从资产目录中将图像呈现为Original

enter image description here

仔细检查您的图片是否尺寸正确。

@ 2x - > 750 x 128

@ 3x - > 1125 x 192

相关问题