iosswiftviewsubviews

centering two views in Navigation titleView


I want my application to behave like this:

enter image description here

It is important to have the exact behavior for my NavigationItem.titleView

I followed these steps so far:

I am creating three views programmatically in my application:

(1) container => holds (2) and (3) => has a gestureRecognizer attached

   let container = UIView(frame: CGRectMake(0,0,200,40))

(2) imageContainer => has an image

        let imageContainer = UIImageView(frame: CGRectMake(0, 0, 30, 30))
        imageContainer.image = UIImage(named: "mock.jpg")

(3) textContainer => has some text

        let textContainer = UILabel(frame: CGRectMake(0,0, 180, 20))
        textContainer.text = "Group xY"

Following I am setting the center of the images to align them:

    imageContainer.center = CGPointMake(container.frame.size.width  / 2,
        container.frame.size.height / 2)
textContainer.center = CGPointMake(container.frame.size.width  / 2,
            container.frame.size.height / 2)

Now I am adding all the subViews to my View and setting

self.navigationItem.titleView = (1)

Starting the app shows, that the titleView's elements aren't properly aligned

enter image description here

Is there a way to implement this exact behavior correctly?

Note: don't worry about the circular image. I know how to implement this.


Solution

  • You should set the size of textContainer to be closer to the bounds of the text. You can do this by calling sizeToFit then you need to set the imageContainer to be on the left of the text so the center of the image should be half the width of the image plus a buffer from the start of the text. You could do that by saying imageContainer.center = CGPointMake(textContainer.frame.minX - imageContainer.frame.size.width * 0.5 - buffer,container.frame.size.height / 2). Your code should look something like:

    let container = UIView(frame: CGRectMake(0,0,200,40))
    let buffer:CGFloat = 8.0
    let maxWidth:CGFloat = 120.0
    
    let imageContainer = UIImageView(frame: CGRectMake(0, 0, 30, 30))
    imageContainer.image = UIImage(named: "profile.jpg")
    
    let textContainer = UILabel(frame: CGRectMake(0,0, 180, 20))
    textContainer.text = "Group xY"
    textContainer.adjustsFontSizeToFitWidth = true
    textContainer.minimumScaleFactor = 0.95
    
    textContainer.sizeToFit()
    textContainer.frame.size.width = min(maxWidth, textContainer.frame.size.width)
    textContainer.center = CGPointMake(container.frame.size.width  / 2,
                                       container.frame.size.height / 2)
    imageContainer.center = CGPointMake(textContainer.frame.minX - imageContainer.frame.size.width * 0.5 - buffer,
                                        container.frame.size.height / 2)
    
    container.addSubview(imageContainer)
    container.addSubview(textContainer)
    

    Which will give you enter image description here for your container.