ios - 如何使用 .center 将 subview 放置在父 View 的中心?

标签 ios swift center subview frames

我有两个 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)

}

这是一个屏幕: enter image description here

最佳答案

为秒 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/

相关文章:

android - 动画在设备上不流畅

html - 在不知道尺寸的情况下垂直居中图像

iphone - 在 xcode 中创建自定义 segue

ios - 在保持宽高比的同时将图像调整为特定大小,必要时裁剪图像(iOS)

android - flutter : Picasso or Universal Image loader equivalent

swift - 可选变量如何成为 "powerful solution"?

ios - 遍历数组并在 Swift 中增加计数器

ios - 根据与位置的距离计算 MAX 和 MIN 纬度和经度 - Objective-C

html - 在 HTML 中绝对居中表格

css:按 block 裁剪的图像。在可见区域周围绘制边框。不平凡的问题