当前位置:  开发笔记 > 后端 > 正文

如何在Swift中心UILabel?

如何解决《如何在Swift中心UILabel?》经验,为你挑选了4个好方法。

我试图集中一些文字,但我似乎没有工作.

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.
    }

}

这是我正在使用的代码,但这是我得到的:

在此输入图像描述

它不是屏幕的中心.有人能告诉我我做错了什么吗?



1> Rashwan L..:

要使UILabel居中,只需添加此行即可

x和y:

title.center = self.view.center

X:

title.center.x = self.view.center.x

Y:

title.center.y = self.view.center.y


这就像一个魅力!非常感谢!

2> 8HP8..:
自动布局

要使您的应用程序面向未来,请使用自动布局锚点而不是设置框架.

1.禁用translatesAutoresizing

titleLabel.translatesAutoresizingMaskIntoConstraints = false

2.添加CenterX和CenterY约束

titleLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true

titleLabel.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true

3.将UILabel的文本对齐方式设置为居中

titleLabel.textAlignment = .center

预习



3> 小智..:

实际上你正在做的是在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)



4> Devbot10..:

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
}

推荐阅读
大大炮
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有