Ios 如何使用Swift将UIImageView水平或垂直设置在屏幕中心,但不再使用故事板
我正试图将一个Ios 如何使用Swift将UIImageView水平或垂直设置在屏幕中心,但不再使用故事板,ios,swift,uiimageview,Ios,Swift,Uiimageview,我正试图将一个UIImageView水平放置在屏幕的上中心,它正在viewDidLoad()中编码。我有两个预先计划,这意味着我不知道指定的函数或API 1) 。我想设置一个等于屏幕宽度一半的变量。我知道这会和“边界”或“框架”有关。不幸的是,我不知道这些函数或参数是如何指定的 2) 。为了确保分辨率,我想计算出currentDevice。之后,我可以使用CGRectMake((分辨率.x)/2,y,长度,宽度)设置UIImageView。是否有任何功能可以确认当前设备 我认为第一个比第二个更有
UIImageView
水平放置在屏幕的上中心,它正在viewDidLoad()
中编码。我有两个预先计划,这意味着我不知道指定的函数或API
1) 。我想设置一个等于屏幕宽度一半的变量。我知道这会和“边界”或“框架”有关。不幸的是,我不知道这些函数或参数是如何指定的
2) 。为了确保分辨率,我想计算出currentDevice
。之后,我可以使用CGRectMake((分辨率.x)/2,y,长度,宽度)
设置UIImageView
。是否有任何功能可以确认当前设备
我认为第一个比第二个更有效
非常感谢您的帮助和指导
Ethan Joe因此,最好的解决方案是利用自动布局。 假设您的
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轴上的图像视图中心设置为与x轴和y轴上的视图中心相同
要按1)中的建议查找视图的宽度,请执行以下操作:
var screenWidth = self.view.bounds.width
我建议使用自动布局:
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。我建议你研究一下自动布局,这是一个很好的功能
这里有一个不错的链接,您可以从中开始:
谢谢你,伙计!我是iOS开发新手,还没有学会自动布局。但我马上就要试一试了@很酷,有用吗?如果你需要更多的帮助,一定要直接问。是的,它奏效了!我用了“界限”的方式。我将尝试自动布局后,我做了一些阅读与它。再次感谢@太棒了!你能接受我的回答吗?谢谢,你肯定会发现它非常有用!很乐意帮忙。