gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 00:16:47 26 4
gpt4 key购买 nike

我试图将 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com