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

标签 ios swift uiimageview

我试图将 UIImageView 水平放置在屏幕的上部中心,它在 viewDidLoad( ) 中编码。而且我有两个预案,这意味着我不知 Prop 体的功能或API。

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

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

而且我认为第一个比第二个更有效率。

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

伊桑·乔

最佳答案

我建议使用自动布局:

    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,这是一个不错的功能。

这是一个很好的链接,您可以从中开始: Learning to love Auto Layout... Programmatically

关于ios - 如何使用 Swift 在屏幕中央水平或垂直设置 UIImageView,但不再使用 StoryBoard,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29099735/

相关文章:

ios - 使用循环向多个 UIImageView 添加属性

ios - 为什么在 Swift 中初始化类时不需要所有对象?

swift - 当我手动传递值时,以下代码有效,但当我解开该值时,以下代码失败

ios - 打开共享 View 后背景 View 卡住

swift - 无法读取属性 'keyCode' 'character' 检测修改键+数字键时断言失败

iphone - 无法在 didFinishLaunchingWithOptions 中制作动画

objective-c - UIImageView - 固定宽度和灵活高度?

ios - 如何找到 Bridging-Header.h 的路径 - Swift,Xcode

ios - 如果我们从不使用分配指针,有什么办法可以访问已释放的对象?

ios - 水平 UIStackView 中一系列 UILabel 的文本底部对齐