我有两个 subview :紫色的属于一个主视图,它的语法非常好:
sSubview.center = view.center
橙色的属于紫色 View ,相同的语法没有将其正确放置在中心。 你能看出我的错误在哪里吗?
Here is my code:
import UIKit
class ViewController: UIViewController {
var sSubview = UIView()
var sLabel = UILabel()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
view.backgroundColor = UIColor.lightGray
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewDidLayoutSubviews() {
createSimplestSubview()
}
// First subview
func createSimplestSubview() {
sSubview = UIView(frame: CGRect(x: 0, y: 0, width: view.frame.width * 0.9, height: view.frame.height * 0.9))
sSubview.backgroundColor = UIColor.purple // just for test, to make it visible
sSubview.center = view.center // that s pretty easy!
view.addSubview(sSubview)
createSimplestLabel()
}
// Second subview
func createSimplestLabel() {
sLabel = UILabel(frame: CGRect(x: 0, y: 0, width: sSubview.frame.width * 0.3, height: sSubview.frame.height * 0.2))
sLabel.backgroundColor = UIColor.orange // just for test, to make it visible
sLabel.center = sSubview.center
sLabel.text = "This label has to be centered!"
sLabel.textAlignment = .center
sLabel.numberOfLines = 0
sSubview.addSubview(sLabel)
}
最佳答案
为秒 subview 尝试下一个代码:
sLabel.center = CGPoint(x: sSubview.frame.width / 2, y: sSubview.frame.height / 2)
你试图在中心放置一个标签,但它是根据 firstSbuview 框架计算的,其原点不是 0.0
关于ios - 如何使用 .center 将 subview 放置在父 View 的中心?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43961647/