如何使用swift在子视图中居中标签

Posted

技术标签:

【中文标题】如何使用swift在子视图中居中标签【英文标题】:How to center label inside a subview with swift 【发布时间】:2016-03-25 13:04:43 【问题描述】:

我正在尝试使用 uipresentationcontroller api 视图中的呈现来呈现报价,但它不起作用。我究竟做错了什么?另外,如何动态调整呈现视图的大小以适应文本?谢谢。

这是我的代码:

override func presentationTransitionWillBegin() 

    presentedView()!.layer.cornerRadius = 15.0

    //adding label for quote to the presented view
    let label = UILabel(frame: CGRectMake(presentedView()!.frame.origin.x, presentedView()!.frame.origin.y, presentedView()!.bounds.width, presentedView()!.bounds.height))
    label.center = presentedView()!.center
    label.textAlignment = NSTextAlignment.Center
    label.text = readQuotesFromLibrary()
    presentedView()?.addSubview(label)
    //rest of the code dealing with uipresentationcontroller goes here ...

【问题讨论】:

【参考方案1】:

如果您将呈现视图的框架分配给标签,那么为什么需要将呈现视图的中心分配给标签中心。标签将被绘制为呈现视图的框架。

【讨论】:

谢谢。如果我删除中心分配事件,它不能解决问题 好的,让我知道它的背景色是哪个view是presentView? 呈现的视图应该是白色的【参考方案2】:

你的 UILabel 的框架是相对于它的父视图,在这种情况下是呈现视图,而不是呈现视图位于其上的视图。因此,您应该使用以下行实例化标签:

let label = UILabel(frame: CGRectMake(0, 0, presentedView()!.bounds.width, presentedView()!.bounds.height))

这会将UILabel的左上角放置在presentView的左上角,并赋予它与presentView相同的宽度和高度。

【讨论】:

【参考方案3】:

我发现制作 CGRects 有时会产生意想不到的结果,就像你的情况一样。如果您想尝试替代方案,我会推荐布局约束。我相信下面的代码应该适合你。

override func presentationTransitionWillBegin() 

    presentedView()!.layer.cornerRadius = 15.0

    //adding label for quote to the presented view
    let label = UILabel()
    label.text = readQuotesFromLibrary()
    label.textAlignment = NSTextAlignment.Center

    presentedView()!.addSubview(label)
    label.translatesAutoresizingMaskIntoConstraints = false
    label.widthAnchor.constraintEqualToAnchor(presentedView()!.widthAnchor).active = true
    label.heightAnchor.constraintEqualToAnchor(presentedView()!.heightAnchor).active = true
    label.centerXAnchor.constraintEqualToAnchor(presentedView()!.centerXAnchor).active = true
    label.centerYAnchor.constraintEqualToAnchor(presentedView()!.centerYAnchor).active = true

    //rest of the code dealing with uipresentationcontroller goes here ...

如果您也遇到文本换行问题,我不会感到惊讶,因为屏幕截图中的引用不适合presentationView;在这种情况下,您可能想要使用属性字符串并允许字符串跨越多行。有多种方法可以让标签跨越多行;因此,AttributeString 不是唯一的方法。

希望对您有所帮助!抱歉,如果您确实需要采用 CGRect 方式并且觉得这没有用。

【讨论】:

以上是关于如何使用swift在子视图中居中标签的主要内容,如果未能解决你的问题,请参考以下文章

Swift:将标签与另一个控件居中

ScrollView 在子视图 xcode 6 Swift 的顶部添加空间

如何在 Swift 中未知宽度和高度的视图中居中 UIBezierPath 椭圆?

使用 Swift 以编程方式将 UIView 中的标签和图像居中对齐

将标签居中到 imageview (Swift)

使用 Swift 3 Xcode 8 居中对齐多个标签