![](/img/trans.png)
[英]Storyboard Constraints set UIImageView no more than 50% of screen
[英]How to set UIImageView in the center of screen horizontally or vertically with Swift, but no more StoryBoard
我试图在屏幕的上部中心水平放置一个UIImageView
,它在viewDidLoad( )
编码。 我有两个预先计划,这意味着我不知道指定函数或API。
1)。 我想设置一个等于屏幕宽度一半的变量。 而且我知道它会与'边界'或'框架'有关。 可悲的是,我不知道那些指定功能或参数。
2)。 为了确保分辨率,我想弄清楚currentDevice
。 之后,我可以使用CGRectMake((resolution.x)/2, y, length, width)
设置UIImageView
。 有没有任何功能可以确认currentDevice
?
我认为第一个比第二个更有效。
非常感谢您的帮助和指导。
伊桑乔
我建议使用autolayout:
var imageView = UIImageView()
imageView.setTranslatesAutoresizingMaskIntoConstraints(false)
view.addSubview(imageView)
// Create the constraints and add them to a Array
var constraints = [AnyObject]()
// This constraint centers the imageView Horizontally in the screen
constraints.append(NSLayoutConstraint(item: imageView, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.CenterX, multiplier: 1.0, constant: 0.0))
// Now we need to put the imageView at the top margin of the view
constraints.append(NSLayoutConstraint(item: imageView, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.TopMargin, multiplier: 1.0, constant: 0.0))
// You should also set some constraint about the height of the imageView
// or attach it to some item placed right under it in the view such as the
// BottomMargin of the parent view or another object's Top attribute.
// As example, I set the height to 500.
constraints.append(NSLayoutConstraint(item: imageView, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1.0, constant: 500.0))
// The next line is to activate the constraints saved in the array
NSLayoutConstraint.activateConstraints(constraints)
此代码在每个设备中将imageView水平居中。 我建议你调查一下AutoLayout,这是一个不错的功能。
这是一个很好的链接,你可以从它开始: 学习爱自动布局...编程
因此,最好的解决方案是利用自动布局。 假设您的UIImageVew
被定义为var imageView = UIImageView!
。 然后你会做以下事情。
var centerXConst = NSLayoutConstraint(item: imageView, attribute: .CenterX, relatedBy: .Equal, toItem: self.view, attribute: .CenterX, multiplier: 1, constant: 1)
var centerYConst = NSLayoutConstraint(item: imageView, attribute: .CenterY, relatedBy: .Equal, toItem: self.view, attribute: .CenterY, multiplier: 1, constant: 1)
self.view.addLayoutConstraints([centerXConst, centerYConst])
你正在做的是分别在x和y轴上将imageView的中心设置为与x和y轴上的视图中心相同。
要查找1)中建议的视图宽度,请执行以下操作:
var screenWidth = self.view.bounds.width
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.