xcode 如何快速将图像置于状态栏下方?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28160565/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to center an image under the status bar in swift?
提问by XcodeNOOB
I just can't seem to find the right code for it. I want to place an image 20 points under the status bar (this will be the Y) and center it (this would be the X of course). I can easily do it with storyboard but i'm struggling to do it programatically. supposed this is my code:
我似乎无法找到正确的代码。我想在状态栏下放置一个图像 20 点(这将是 Y)并将其居中(这当然是 X)。我可以用故事板轻松地做到这一点,但我正在努力以编程方式做到这一点。假设这是我的代码:
var image: UIImage = UIImage(named: "someImage.png")!
var bgImage = UIImageView(image: image)
//Tried with self.view.frame.size.height but not working
bgImage.frame = CGRect(x: 0, y: self.view.frame.size.height - 20, width: self.view.frame.size.width, height: 64)
//also tried this which not worked as well
// bgImage.center = CGPointMake(self.view.frame.width, self.view.frame.hight - 20)
self.view.addSubview(bgImage)
I've search apple docs but it's so unclear, any help would be appreciated.
我搜索了苹果文档,但不清楚,任何帮助将不胜感激。
回答by Jeffery Thomas
Once bgImagehas the correct size, then the general solution for this is
一旦bgImage有正确的尺寸,那么一般的解决方案是
bgImage.frame.origin.y = 20.0 // 20 down from the top
bgImage.frame.origin.x = (self.view.bounds.size.width - bgImage.frame.size.width) / 2.0 // centered left to right.
回答by Michael Dautermann
how about something like this:
这样的事情怎么样:
var image: UIImage = UIImage(named: "someImage.png")
var new_view = UIView(image: image)
view.addSubview(new_view);
// This is the default setting but be explicit anyway...
new_view.setTranslatesAutoresizingMaskIntoConstraints(true)
new_view.autoresizingMask = UIViewAutoresizing.FlexibleLeftMargin |
UIViewAutoresizing.FlexibleRightMargin
new_view.center = CGPointMake(self.view.frame.size.height - 20, view.bounds.midY)
Which adds the new subview, sets a flexible left & right margin on it and then centers it just under the status bar.
它添加了新的子视图,在其上设置了灵活的左右边距,然后将其居中在状态栏下方。
The programmatic code for which I found in this related question.
我在这个相关问题中找到的编程代码。

