首页 > 解决方案 > 编辑-我怎样才能让 UIlabel 进入容器的中间?

问题描述

我怎样才能让 UIlabel 进入容器的中间?并且该文本和视图同样消失并进入下一个视图。

编辑:这段代码现在对我来说很好

class TestViewController: UIViewController {

let container = UIView()
let redSquare = UIView()
let blueSquare = UIView()
let label = UILabel()


override func viewDidLoad() {
    super.viewDidLoad()


    self.label.textColor = UIColor.orange

    self.label.font = label.font.withSize(25)
    self.label.numberOfLines = 0

    self.label.center = self.blueSquare.center

    self.label.textAlignment = NSTextAlignment.center

    self.label.text =

    "sosdihfiosdfhsdhfdisfhsdfhdsoifhsdofhsdifhdsofhdsofhsdohdsfdosdohdfh"


    self.blueSquare.addSubview(label)

    self.label.frame = CGRect(x: 45, y: 120, width: 300, height: 100)

    self.container.frame = CGRect(x: 7, y: 200, width: 400, height: 500)
    self.view.addSubview(container)
    self.redSquare.frame = CGRect(x: 0, y: 0, width: 400, height: 500)
    self.blueSquare.frame = redSquare.frame

    self.redSquare.backgroundColor = UIColor.darkGray
    self.blueSquare.backgroundColor = UIColor.darkGray
    self.container.addSubview(self.redSquare)
}

标签: swiftxcodelayouttransitionauto

解决方案


定义两个标签,如:

let label = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 30))
let label2 = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 30))

然后在将 redSquare 添加到容器之前在 viewDidLoad() 中修复一些标签的属性并将标签添加到蓝色和红色方块:

label.center = self.redSquare.center
label.textAlignment = NSTextAlignment.center
label.text = "same text"

label2.textAlignment = NSTextAlignment.center
label2.center = self.blueSquare.center
label2.text = "same text"

self.blueSquare.addSubview(label2)
self.redSquare.addSubview(label)

推荐阅读