2017-04-02 137 views
2

在Swift的操場上,我如何將UILabel置於UIViewController的內部?如何在Swift中居中文本?

當我使用title.center = CGPoint(x: vc.view.frame.width/2, y: 20)時,文本會熄滅。

這是問題

problem

如果有幫助,這是我的代碼。

import UIKit 
import PlaygroundSupport 


// Set up ViewController and other things 
var vc = UIViewController() 
vc.view.frame.size.height = 75 
vc.view.backgroundColor = .white 

let title = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 50)) 
title.textAlignment = .center 
title.center = vc.view.center 
title.text = "Which code is correct?" 
vc.view.addSubview(title) 

PlaygroundPage.current.liveView = vc 
+0

嘗試title.center = self.view.center –

+0

@Harambe隊http://stackoverflow.com/questions/ 34645943/how-to-center-uilabel-in-swift –

+0

title.center = GCPoint(x:self.view.bounds.size.width/2.0,y:self.view.bounds.size.height/2.0) –

回答

1

特殊問題迅速操場,則該視圖控制器的實際幀將只正確地更新,視圖之後被裝載/屏幕上顯示。這意味着把線居中行後的標籤設置實時取景應該有所幫助:

PlaygroundPage.current.liveView = vc 
title.center = vc.view.center 
vc.view.addSubview(title) 
0

如果我們談論的層次結構頂視圖(即視圖控制器的觀點),這條線應該是足夠了:

title.center = vc.view.center 

否則,如果你想中心視圖/標籤/按鈕/無論任何視圖控制器視圖的子視圖中 - 下一個解決方案是通用的:如果你想只水平或垂直居中

title.center = CGPoint(x: parentView.bounds.size.width/2, y: parentView.bounds.size.height/2) 

- 修改yx參數CGPoint(x:y:)功能相應的:

// Center horizontally but with vertical offset of 20 points 
title.center = CGPoint(x: parentView.bounds.size.width/2, y: 20 - title.bounds.size.height/2) 
+0

我添加了我的代碼。那些不幸的工作。 –