Search code examples
iosobjective-cswiftxcodexcode8

How to center a logo on SideMenu using Xcode


I want to Center a logo on the SideMenu and this is the code so far:

  UIImageView *logo =[[UIImageView alloc] init];
    logo.image=[UIImage imageNamed:@"menulogo"];
    logo.contentMode = UIViewContentModeScaleToFill;
    logo.layer.cornerRadius = cornerRadius;
    logo.layer.masksToBounds = YES;
    logo.frame = container.bounds;
    [container addSubview:logo];
    [headerView addSubview:container];

Solution

  • Create an extension to UIView

    extension UIView {  
    func constraintToMidCenterXY(of view: UIView) {
        translatesAutoresizingMaskIntoConstraints = false
    
        NSLayoutConstraint.activate([centerXAnchor.constraint(equalTo: view.centerXAnchor),
                                     centerYAnchor.constraint(equalTo: view.centerYAnchor))
    }
    

    }

    Then you can do something like this

    logo.constraintToMidCenterXY(of: container)
    

    Also you should not set logo's frame to container's bounds! that's another problem

    The above is a common approach that you can use, Autolayout. You can also use UIStackView