2016-03-25 51 views
0

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

这是我的代码:

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 ... 

As you can see the text is off }

回答

0

如果您分配呈现视图的标记帧,那么为什么需要分配呈现视图的中心标记center.Label将被画成呈现View的框架。

+0

谢谢。事件,如果我删除中心分配它不能解决问题 – irkinosor

+0

好吧,让我知道其背景颜色是呈现viewView? –

+0

呈现的视图应该是白色的 – irkinosor

0

你UILabel的框架是相对于它的超级视图,在这种情况下,它是呈现视图,而不是呈现在顶部的视图。因此,您应该用线实例标签:

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

这会将左上角的UILabel的presentedView的左上角,并给它相同的宽度和高度为presentedView。

0

我发现制作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,我不会感到惊讶;在这种情况下,您可能需要使用一个属性字符串并允许该字符串跨越多行。有多种方法可以让标签跨越多行;所以一个归属串不是唯一的方法来做到这一点。

我希望有帮助!对不起,如果你真的需要去CGRect的方式,并没有发现这有用。