How to place a subview in the center of parent view using .center?
Asked Answered
O

2

6

I have two subviews: the purple one belongs to a main view and it works wonderful with the syntax:

sSubview.center = view.center 

The orange one belongs to the purple view and the same syntax doesn't place it correctly in the center. Could you see where my mistake is?

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)

}

}

Here is a screen: enter image description here

Operetta answered 14/5, 2017 at 7:57 Comment(0)
S
8

Try the next code for seconds subview:

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

You're trying to place a label in the center, but it calculated according to the firstSbuview frame, which origin is not 0.0

Sarge answered 14/5, 2017 at 8:10 Comment(0)
H
3

A better way is to use convertPoint as the problem with your code is that the coordinate spaces are sometimes different.

sSubview.center = view.superview.convert(view.center, to: sSubview.superview)

view.center is in the coordinate space of view.superview

sSubview.center is in the coordinate space of sSubview.superview

Hydrocellulose answered 14/5, 2017 at 9:38 Comment(2)
It works, thank you! Only a small correction in your code: sSubview.center = (view.superview?.convert(view.center, to: sSubview.superview))! Perhaps, it is the newest version of swift :)Operetta
I wrote it from memory, sorry. I would use guard let instead of !Hydrocellulose

© 2022 - 2024 — McMap. All rights reserved.