UIView中的中心标签,其y偏移状态栏的高度

时间:2017-05-28 15:40:05

标签: ios swift uiview

我很擅长快速尝试将标签和图像置于屏幕顶部的UIView中心。目前标签是垂直和水平居中的,因为这是我现在唯一可以做的事情。如您所见,我将autoresizing mask设置为约束为false并使用了centerXAnchor和-YAnchor。

但实际上我并不希望标签位于PostView的中心,而是以状态栏高度的y偏移为中心。所以它居中但没有y偏移状态栏的高度。因此,它看起来有点局促(?):它非常接近状态栏...它看起来像这样:

centered but with no y offset of the height of the statusbar

但是我希望标签(以及后来的图像)在红色框中垂直居中:

The label shall be centered within the red box

这是我现在的代码(PostView class):

override init(frame: CGRect){

    super.init(frame: frame)

    //add subview containing name (and image)
    infosContainerView.frame = frame
    addSubview(infosContainerView)

    //add sub view containing label to former UIView (infosContainerView)
    infosContainerView.addSubview(infoNameView)
    infoNameView.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true
    infoNameView.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true

}

//this UIView shall contain the infoNameView and infoImageView
let infosContainerView: UIView = {

    //set properties of controls container view
    let entireInfoView = UIView()
    entireInfoView.backgroundColor = .white

    return entireInfoView

}()


//label and properties of label with name (autoresizingmaskinto constraint set to false)
let infoNameView: UILabel = {

    //set properties of controls container view
    let nameView = UILabel()

    nameView.translatesAutoresizingMaskIntoConstraints = false
    nameView.backgroundColor = .white

    nameView.font = UIFont(name: "HelveticaNeue", size: 20)

    nameView.text = "Name"
    nameView.textColor = .black
    nameView.textAlignment = .center

    return nameView

}()

编辑:

JožeWs已接近解决问题,而不是除以2,必须除以4虽然我不知道为什么......:

let statusBarHeight = UIApplication.shared.statusBarFrame.height

infosContainerView.addSubview(infoNameView)
infoNameView.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true
infoNameView.centerYAnchor.constraint(equalTo: centerYAnchor, constant: statusBarHeight/4).isActive = true

截图:

Solution

1 个答案:

答案 0 :(得分:1)

替换centerYAnchor约束init
// infoNameView.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true

   let statusBarHeight = UIApplication.shared.statusBarFrame.height
   infoNameView.centerYAnchor.constraint(equalTo: centerYAnchor, constant: statusBarHeight/2).isActive = true

这会将centerYAnchor的偏移量添加到等于statusBarHeight

的值