![](/img/trans.png)
[英]How to add subView to anotherSubView with center alignment in iOS swift.
[英]How to center label inside a subview with swift
我正在嘗試使用從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 ...
如果您要將展示視圖的框架分配給標簽,那么為什么需要將展示視圖的中心分配給標簽中心。標簽將作為展示視圖的框架繪制。
UILabel的框架是相對於其超級視圖的,在這種情況下,它是presentedView,而不是presentedView位於其頂部的視圖。 因此,您應該使用以下行實例化標簽:
let label = UILabel(frame: CGRectMake(0, 0, presentedView()!.bounds.width, presentedView()!.bounds.height))
這會將UILabel的左上角放在presentedView的左上角,並為其提供與presentedView相同的寬度和高度。
我發現制作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。 在這種情況下,您可能需要使用attributedString並允許字符串跨越多行。 有多種方法可以使標簽跨越多行。 因此,attributedString不是唯一的方法。
希望對您有所幫助! 抱歉,如果您確實需要使用CGRect方式,並且覺得此功能沒有用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.