2016-09-27 21 views
0

我有2 UILabel s。 lbl1的文字可以改變,而lbl2的文字是靜態的。ios autolayout:動態寬度應該用SnapKit按下第二個標籤,正確的方式

它們最初都設置在同一行上。我有lbl1numberOfLines設置爲0(無限)。當lbl1的寬度侵入lbl2的空間時,我想lbl2向下推並將其頂部對齊到lbl1的底部。我有一個當前的解決方案,但覺得有一個純粹的自動佈局方式我錯過了。任何幫助將是偉大的!

兩個標籤適合在1號線:

enter image description here

lbl2不會在純自動佈局在我嘗試下移:

enter image description here

期望:

enter image description here

當前解決方案的工作,但感覺非理想:

import XCPlayground 
import SnapKit 
import UIKit 

let screen: UIView = UIView(frame: CGRectMake(0,0,320,568)) 
XCPlaygroundPage.currentPage.liveView = screen 
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true 

let lbl1: UILabel = UILabel() 
lbl1.text = "Short Text asnoetuha 1 1 1 1 " 
lbl1.numberOfLines = 0 
lbl1.backgroundColor = UIColor.whiteColor() 

let lbl2: UILabel = UILabel() 
lbl2.text = "Amount Text" 
lbl2.backgroundColor = UIColor.yellowColor().colorWithAlphaComponent(0.5) 

screen.addSubview(lbl1) 
screen.addSubview(lbl2) 

lbl1.snp_makeConstraints { (make: ConstraintMaker) in 
    make.top.leading.equalTo(screen) 
    make.width.lessThanOrEqualTo(screen.snp_width) 
} 

lbl2.snp_makeConstraints { (make: ConstraintMaker) in 
    // Below lines feel un-ideal 
    let lbl2X: CGFloat = screen.frame.width - lbl2.intrinsicContentSize().width 
    let lbl1RightX: CGFloat = screen.frame.origin.x + lbl1.intrinsicContentSize().width 
    let hasOverlap: Bool = lbl1RightX >= lbl2X 

    make.top.equalTo(hasOverlap ? lbl1.snp_bottom : lbl1.snp_top).priorityLow() 
    make.trailing.equalTo(screen) 
} 

回答

-1

我相信你是不是這個接近正確的方式。你應該可以創建一個函數來監聽lbl1的右錨點是否與lbl2的左錨點(使用SnapKit非常容易)接觸。

發生這種情況時,您可以調用一個函數,將約束重新映射爲適合您提供的圖像。這是通過調用snap_updateConstraints或snp_remakeConstraints完成的。那麼你的約束代碼應該是直線前進的,因爲你只需將lbl1的底部錨點固定到lbl2的頂部錨點,然後進行其他約束直到獲得期望的效果。