简体   繁体   English

Swift:以编程方式对齐不同IOS屏幕尺寸的标签

[英]Swift: programmatically align labels for different IOS screen sizes

I'm new to Swift and ios development. 我是Swift和ios开发的新手。 I have 6 labels and a horizontal SKScene in my App. 我的应用程序中有6个标签和一个水平SKScene。 I would like to align those 6 labels beautifully and automatically. 我想精美地自动对齐这6个标签。 Now I have fixed the positions and the alignment always looks awful on some screen size while good on other. 现在我已经修复了位置,并且对齐在某些屏幕尺寸上看起来总是很糟糕,而在另

I have not used storyboards or other graphical editors for building the ui but everything is done in code. 我没有使用故事板或其他图形编辑器来构建ui,但一切都是在代码中完成的。 Therefore I'm looking for a programmatic solution (code examples) for handling the alignment. 因此,我正在寻找一种用于处理对齐的程序化解决方案(代码示例)。

If you want to place them in the middle of the screen horizontally, but give them different y positions, you could just do something like this for each label: 如果你想将它们水平放置在屏幕中间,但是给它们不同的y位置,你可以为每个标签做这样的事情:

label.position = CGPointMake(CGRectGetMidX(self.frame),CGRectGetMaxY(self.frame) * 0.80)

To place them at different y positions, just multiply by the maxY by a different decimal number. 要将它们放在不同的y位置,只需将maxY乘以不同的十进制数。 This way, all of the labels are aligned along the x-axis and appear at different y-positions, like a column and they will appear this way on every screen size because they are positioned relative to the screen size and not in a fixed position. 这样,所有标签都沿着x轴对齐并出现在不同的y位置,就像一列,它们将以这种方式出现在每个屏幕尺寸上,因为它们相对于屏幕尺寸而不是固定位置。

You can align the labels (lets say at the center of the screen) like this. 您可以像这样对齐标签(例如在屏幕中央)。

var label1 = UILabel(CGRectMake: 0, 0, 200, 40)
label1.center = CGPointMake(UIScreen.mainScreen().bounds.size.width/2, 30)

var label2 = UILabel(CGRectMake: 0, 0, 200, 40)
label2.center = CGPointMake(UIScreen.mainScreen().bounds.size.width/2, label1.center.y + 30)

and so on. 等等。 Just reference the main screen bounds and not static points for alignment, so that they are centered in any screen size. 只需引用主屏幕边界而不是静态点进行对齐,以便它们以任何屏幕大小为中心。

What I ended up doing was to create an empty SKSprite to which I included the SKLabels. 我最终做的是创建一个空的SKSprite,我包含了SKLabels。 Now I can control by the pixed the distances between labels but align the top-level sprite in the middle of the screen despite screen size. 现在我可以通过像素控制标签之间的距离,但是尽管屏幕大小,仍然将屏幕中间的顶级精灵对齐。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM