【问题标题】:Vertically center UILabel in parent UIView在父 UIView 中垂直居中 UILabel
【发布时间】:2015-03-12 18:03:06
【问题描述】:

如何在 UILabel 的父 UIView 中垂直(y 轴)居中而不改变 UILabel 的水平位置?

以下不是它(它改变了x轴):

[self.label setCenter:CGPointMake(view.frame.size.width / 2, view.frame.size.height / 2)]

再次,我希望沿 y 轴居中。

【问题讨论】:

    标签: ios iphone xcode uiview uilabel


    【解决方案1】:
    CGPoint center = self.label.center;
    center.y = view.frame.size.height / 2;
    [self.label setCenter:center];
    

    快速回答..

    var center : CGPoint = self.titleLbl.center
            center.y = self.frame.size.height / 2
            self.titleLbl.center = center
    

    【讨论】:

    • 没有。这没有做到。
    • 它做了什么?至于输出是什么?
    • 什么也没改变。但后来我意识到数学有点不对劲。但是您的总体想法是正确的,所以谢谢。正确的数学是CGFloat padding = (parent.frame.size.height-self.label.frame.size.height)/2; center.y +=padding;
    【解决方案2】:

    我宁愿建议在这种情况下应用自动布局约束。下面的约束将在父视图的中心垂直对齐。在第二个约束中,我将值 20 作为 x 坐标。您可以将其替换为您自己的值。

    NSLayoutConstraint *constraintY = [NSLayoutConstraint constraintWithItem:self.label attribute:NSLayoutAttributeCenterY
                          relatedBy:NSLayoutRelationEqual toItem:view
                          attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:0.0];
    [view addConstraint:constraintY];
    NSLayoutConstraint *constraintX = [NSLayoutConstraint constraintWithItem:self.label attribute:NSLayoutAttributeLeading
                              relatedBy:NSLayoutRelationEqual toItem:view
                              attribute:NSLayoutAttributeLeading multiplier:1.0 constant:20.0];
    [view addConstraint:constraintX];
    

    【讨论】:

    • 恕我直言,省去麻烦,永远远离自动布局。尝试使用内部界面构建器已经够糟糕的了,以编程方式搞砸它只会糟糕一千倍。
    猜你喜欢
    • 2014-09-17
    • 1970-01-01
    • 2014-05-27
    • 1970-01-01
    • 1970-01-01
    • 2015-07-06
    • 2015-08-25
    • 2013-08-01
    • 1970-01-01
    相关资源
    最近更新 更多