将UIImage垂直居中对齐

问题描述 投票:0回答:2

我正在尝试使用Swift将图像垂直居中对齐。我了解您是通过使用约束来做到这一点的,但是我一直无法使它起作用。

func getLogo() {
    let logo = UIImage(named: "LogoWhite")
    let logoView = UIImageView(image: logo)
    logoView.contentMode = .scaleAspectFit

    self.addSubview(logoView)
}
ios swift
2个回答
0
投票

我建议在UIView上使用扩展名,以使自动布局更加容易。对于这样一个简单的任务,这似乎是很多代码开始的,但是从长远来看,这些便利功能将使事情变得更快,例如:

public func anchor(top: NSLayoutYAxisAnchor?, leading: NSLayoutXAxisAnchor?, bottom: NSLayoutYAxisAnchor?, trailing: NSLayoutXAxisAnchor?, padding: UIEdgeInsets = .zero, size: CGSize = .zero){

        translatesAutoresizingMaskIntoConstraints = false

        //Set top, left, bottom and right constraints
        if let top = top {
            topAnchor.constraint(equalTo: top, constant: padding.top).isActive = true
        }
        if let leading = leading {
            leadingAnchor.constraint(equalTo: leading, constant: padding.left).isActive = true
        }
        if let bottom = bottom {
            bottomAnchor.constraint(equalTo: bottom, constant: -padding.bottom).isActive = true
        }
        if let trailing = trailing {
            trailingAnchor.constraint(equalTo: trailing, constant: -padding.right).isActive = true
        }

        //Set size contraints
        if size.width != 0 {
            widthAnchor.constraint(equalToConstant: size.width).isActive = true
        }
        if size.height != 0 {
            heightAnchor.constraint(equalToConstant: size.height).isActive = true
        }
    }

然后您可以简单地致电:

someUIView.anchor(anchor(top: topAnchor, leading: leadingAnchor, bottom: bottomAnchor, trailing: nil, padding: .init(top: 16, left: 16, bottom: 16, right: 16), size: .init(width: 80, height: 80))

然后直接回答您的问题,您可以添加更多扩展名以轻松地完成某些工作:

public func anchorCenterXToSuperview(constant: CGFloat = 0) {
        translatesAutoresizingMaskIntoConstraints = false
        if let anchor = superview?.centerXAnchor {
            centerXAnchor.constraint(equalTo: anchor, constant: constant).isActive = true
        }
    }

最后,您可以简单地在任何anchorCenterXToSuperview()上调用UIView以居中任何对象。

在尝试布局视图之前,请不要忘记确保已将视图添加到视图层次结构中,否则会出现错误。

希望这会有所帮助!


0
投票

如果您不想使用约束(我个人不喜欢它们),可以检查容器中心并将UIImageView放在此处。

示例:

containerView->包含您的logo的视图

徽标->您要垂直居中的视图

logo.center.y = containerView.center.y

如果containerView是屏幕,则

let screen = UIScreen.main.bounds
let height = screen.height
logo.center.y = screen.height / 2
© www.soinside.com 2019 - 2024. All rights reserved.