HTML5   发布时间:2022-04-27  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了ios – 如何使用.center将子视图放在父视图的中心?大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我有两个子视图:紫色的属于主视图,它的语法很好用:

sSubview.center = view.center

橙色属于紫色视图,相同的语法不能正确放置在中心.
你能看出我的错误在哪里吗?

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,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)

}

}

这是一个屏幕:

ios – 如何使用.center将子视图放在父视图的中心?

解决方法

尝试使用秒子视图的下一个代码

sLabel.center = CGPoint(x: sSubview.frame.width / 2,y: sSubview.frame.height / 2)

您正在尝试在中心放置一个标签,但它是根据firstSbuview框架计算的,该框架的原点不是0.0

大佬总结

以上是大佬教程为你收集整理的ios – 如何使用.center将子视图放在父视图的中心?全部内容,希望文章能够帮你解决ios – 如何使用.center将子视图放在父视图的中心?所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。