我正试着把一些文字放在中心,但我觉得它似乎不起作用.

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

}

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

enter image description here

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

推荐答案

要居中放置标签,只需添加此行

x and y:

title.center = self.view.center

x:

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

y:

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

Swift相关问答推荐

使用SWIFT宏从另一个枚举添加 case

按变换zoom 在UIView中不起作用

阻塞(受CPU限制的)任务的异步功能?

如何在SwiftUI的文本视图中显示NSMutableAttributedString?

SwiftUI 中的同一个 ForEach 中是否可以有 2 个数组?

为什么我的Swift app不能用xcodebuild构建,但是用XCode可以构建?

如何在 swift 5.0 中获取当前行

是否有一个带有空初始值设定项的 Swift 类/ struct 的标准协议

SwiftUI 分段 Select 器的问题

如何更新 UserDefault 中的特定值

Swift - 给定一个像 30 的 Int 如何将范围数乘以 7?

Swift 非参与者隔离闭包

使用列表的下一项更新相同的视图

SwiftUI 4 列表初始化程序在 iOS 中不可用

是否可以在 Swift 中创建通用闭包?

如何快速截取 UIView 的屏幕截图?

CMutablePointer - 如何访问它?

快速覆盖属性

通过单击表格视图中的单元格打开新的视图控制器 - Swift iOS

保持窗口始终在顶部?