gpt4 book ai didi

swift - 将 UILabel 放置在屏幕中央

转载 作者:行者123 更新时间:2023-12-05 08:19:02 25 4
gpt4 key购买 nike

我有一个 UILabel,无论在哪个 iPhone 上播放它,我都希望它显示在屏幕中央!

但是我做不对!它总是在别的地方,但不在中间。

我做错了什么?

这是正在发生的事情的图片和代码!

so not in the middle!

class end: SKScene {

var label = UILabel()


override func didMoveToView(view: SKView) {
scene?.backgroundColor = UIColor(red: CGFloat(59.0/255.0), green: CGFloat(89.0/255.0), blue: CGFloat(152.0/255.0), alpha: CGFloat(1.0))

let w = UIScreen.mainScreen().bounds.width
let h = UIScreen.mainScreen().bounds.height
label = UILabel(frame: CGRect(x: w / 2, y: h / 2, width: 120, height: 30))
label.text = "REPLAY"
label.center = CGPoint(x: w / 2, y: 2)
label.textColor = UIColor.whiteColor()
self.view?.addSubview(label)

最佳答案

我认为您的标签实际上居中。

如果我像这样添加红色背景色:

label.backgroundColor = UIColor.redColor()

并将垂直中心更改为屏幕中心,即在您的示例中更改此行:

label.center = CGPoint(x: w / 2, y: 2)

为此:

label.center = CGPoint(x: w / 2, y: h / 2)

我最终得到了这个:

centered label but not centered text

所以,标签实际上是居中的。然而,文本并未在标签中居中,这使得当您没有背景颜色时,文本看起来好像没有居中。

如果我将 textAlignment 更改为 .Center 并再次删除背景色,我将得到以下结果:

centered text in centered label

最终的代码示例如下所示:

override func didMoveToView(view: SKView) {
scene?.backgroundColor = UIColor(red: CGFloat(59.0/255.0), green: CGFloat(89.0/255.0), blue: CGFloat(152.0/255.0), alpha: CGFloat(1.0))

let w = UIScreen.mainScreen().bounds.width
let h = UIScreen.mainScreen().bounds.height

label = UILabel(frame: CGRect(x: w / 2, y: h / 2, width: 120, height: 30))
label.text = "REPLAY"
label.center = CGPoint(x: w / 2, y: h / 2)
label.textAlignment = .Center
label.textColor = UIColor.whiteColor()
self.view?.addSubview(label)
}

说了这么多,也许你应该看看 SKLabelNode正如@whirlwind 在评论中建议的那样,这样你的标签就成为了 SKScene 的一个组成部分,而不是用 bolt 固定在外部 UIView 上的东西(如果这对你)。

希望对你有帮助。

关于swift - 将 UILabel 放置在屏幕中央,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38940604/

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