如何使用Swift在屏幕中心水平或垂直设置UIImageView,但不再使用StoryBoard

Eth*_*Joe 2 uiimageview ios swift

我试图UIImageView在屏幕的上部中心水平放置编码viewDidLoad( ).我有两个预先计划,这意味着我不知道指定函数或API.

1).我想设置一个等于屏幕宽度一半的变量.而且我知道它会与'边界'或'框架'有关.可悲的是,我不知道那些指定功能或参数.

2).为了确保分辨率,我想弄清楚currentDevice.在那之后,我可以设置UIImageView使用CGRectMake((resolution.x)/2, y, length, width).有什么功能可以确认currentDevice吗?

我认为第一个比第二个更有效.

非常感谢您的帮助和指导.

伊桑乔

Alv*_*aro 5

我建议使用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)
Run Code Online (Sandbox Code Playgroud)

此代码在每个设备中将imageView水平居中.我建议你调查一下AutoLayout,这是一个不错的功能.

这是一个很好的链接,你可以从它开始: 学习爱自动布局...编程