我试图集中一些文字,但我似乎没有工作.
import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. let title = UILabel() title.text = "Some Sentence" title.numberOfLines = 0 title.frame = CGRectMake(self.view.bounds.size.width/2,50,self.view.bounds.size.width, self.view.bounds.size.height) // x , y, width , height title.textAlignment = .Center title.sizeToFit() title.backgroundColor = UIColor.redColor() self.view.addSubview(title) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
这是我正在使用的代码,但这是我得到的:
它不是屏幕的中心.有人能告诉我我做错了什么吗?
要使UILabel居中,只需添加此行即可
x和y:
title.center = self.view.center
X:
title.center.x = self.view.center.x
Y:
title.center.y = self.view.center.y
要使您的应用程序面向未来,请使用自动布局锚点而不是设置框架.
titleLabel.translatesAutoresizingMaskIntoConstraints = false
titleLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true titleLabel.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
titleLabel.textAlignment = .center
实际上你正在做的是在UILabel中输入文本.你想要做的是集中标签.要做到这一点,你可以这样做:
title.frame.origin = CGPoint(x: x, y: y)
如果你想让水平居中,你可以做到:
title.frame.origin = CGPoint(x: self.view.frame.width / 2, y: yValue)
此外,如果您想将标签的x和y值居中,您可以这样做:
title.frame.origin = CGPoint(x: self.view.frame.width / 2, y: self.view.frame.height / 2)
SWIFT 4
This worked for me and seems more future proof. This also works for a multi-line label.
override func loadView() { self.view = UIView() let message = UILabel() message.text = "This is a test message that should be centered." message.translatesAutoresizingMaskIntoConstraints = false message.lineBreakMode = .byWordWrapping message.numberOfLines = 0 message.textAlignment = .center self.view.addSubview(message) message.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true message.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true message.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true }