Ios 如何在Swift中居中显示文本?
在快速运动场中,如何将Ios 如何在Swift中居中显示文本?,ios,swift3,swift-playground,Ios,Swift3,Swift Playground,在快速运动场中,如何将UILabel置于UIViewController内 当我使用title.center=CGPoint(x:vc.view.frame.width/2,y:20)时,文本会从屏幕上消失 这就是问题所在 如果有帮助,这是我的代码 import UIKit import PlaygroundSupport // Set up ViewController and other things var vc = UIViewController() vc.view.frame.
UILabel
置于UIViewController
内
当我使用title.center=CGPoint(x:vc.view.frame.width/2,y:20)
时,文本会从屏幕上消失
这就是问题所在
如果有帮助,这是我的代码
import UIKit
import PlaygroundSupport
// Set up ViewController and other things
var vc = UIViewController()
vc.view.frame.size.height = 75
vc.view.backgroundColor = .white
let title = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 50))
title.textAlignment = .center
title.center = vc.view.center
title.text = "Which code is correct?"
vc.view.addSubview(title)
PlaygroundPage.current.liveView = vc
如果我们讨论的是层次结构中的俯视图(即视图控制器的视图),那么这一行就足够了:
title.center = vc.view.center
否则,如果要将视图/标签/按钮/任何视图控制器视图的子视图居中,则下一个解决方案是通用的:
title.center = CGPoint(x: parentView.bounds.size.width / 2, y: parentView.bounds.size.height / 2)
如果只想水平或垂直居中-相应地修改CGPoint(x:y:)
函数的y
或x
参数:
// Center horizontally but with vertical offset of 20 points
title.center = CGPoint(x: parentView.bounds.size.width / 2, y: 20 - title.bounds.size.height / 2)
swift游乐场的特殊问题是,只有在屏幕上加载/显示视图后,视图控制器的实际帧才会正确更新。这意味着将标签居中的线放在设置实时视图的线之后应有助于:
PlaygroundPage.current.liveView = vc
title.center = vc.view.center
vc.view.addSubview(title)
尝试title.center=self.view。center@Harambe队名.center=GCPoint(x:self.view.bounds.size.width/2.0,y:self.view.bounds.size.height/2.0)可能的重复项仍不工作