我正试图将一些文字放在中心,但我似乎没有工作。
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.
}
}
这是我正在使用的代码,但这就是我得到的:
它不是屏幕的中心。有人能告诉我我做错了什么吗?
答案 0 :(得分:49)
要使UILabel居中,只需添加此行
即可x和y:
title.center = self.view.center
<强> X 强>
title.center.x = self.view.center.x
<强> Y:强>
title.center.y = self.view.center.y
答案 1 :(得分:12)
要使您的应用具有未来的发展前景,请使用自动布局锚点而不是设置框架。
implementation 'com.google.firebase:firebase-auth:16.0.1'
titleLabel.translatesAutoresizingMaskIntoConstraints = false
titleLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
titleLabel.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
答案 2 :(得分:6)
实际上你正在做的是输入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)
答案 3 :(得分:4)
SWIFT 4
这对我有用,并且似乎更能证明未来。这也适用于多行标签。
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
}
答案 4 :(得分:0)
var noDataLbl: UILabel?
noDataLbl = UILabel(frame: CGRect(x: 0, y: self.view.center.y, width: 290, height: 70))
noDataLbl?.textAlignment = .center
noDataLbl?.font = UIFont(name: "Halvetica", size: 18.0)
noDataLbl?.numberOfLines = 0
noDataLbl?.text = "Replace this with your text."
noDataLbl?.lineBreakMode = .byTruncatingTail
view.addSubview(noDataLbl!)
noDataLbl?.isHidden = false
noDataLbl?.center = self.view.center