我想將幾個多行標籤添加到UIStackView
。UIStackView和截斷的Multiline UILabels
這裏是我的代碼。首先,我創建父/母StackView,把它放到一個滾動型(其被捲起到屏幕)
stackView = UIStackView()
stackView.axis = .Vertical
stackView.distribution = .Fill
stackView.spacing = 2
stackView.translatesAutoresizingMaskIntoConstraints = false
scrollView.addSubview(stackView)
NSLayoutConstraint.activateConstraints(stackConstraints)
let s1 = createHeaderStackView()
stackView.insertArrangedSubview(s1, atIndex: 0)
let lbl2 = makeLabel()
lbl2.text = "Second One"
stackView.insertArrangedSubview(lbl2, atIndex: 1)
scrollView.setNeedsLayout()
而makeLabel
和makeButton
只是輔助功能
func makeButton() -> UIButton {
let btn = UIButton(type: .Custom)
btn.backgroundColor = UIColor.lightGrayColor()
return btn
}
func makeLabel() -> UILabel {
let lbl = UILabel()
lbl.font = UIFont.systemFontOfSize(18)
lbl.setContentCompressionResistancePriority(1000, forAxis: .Vertical)
lbl.setContentHuggingPriority(10, forAxis: .Vertical)
lbl.preferredMaxLayoutWidth = scrollView.frame.width
lbl.numberOfLines = 0
lbl.textColor = UIColor.blackColor()
lbl.backgroundColor = UIColor.redColor()
return lbl
}
的createHeaderStackView
方法是配置我的StackView把所有我的頭文件放入StackView中。
func createHeaderStackView() -> UIStackView {
let lblHeader = makeLabel()
lblHeader.text = "UIStackView"
lblHeader.textAlignment = .Center
let lblInfo = makeLabel()
lblInfo.text = "This is a long text, over several Lines. Because why not and am able to to so, unfortunaltey Stackview thinks I'm not allowed."
lblInfo.textAlignment = .Natural
lblInfo.layoutIfNeeded()
let lblInfo2 = makeLabel()
lblInfo2.text = "This is a seconds long text, over several Lines. Because why not and am able to to so, unfortunaltey Stackview thinks I'm not allowed."
lblInfo2.textAlignment = .Natural
lblInfo2.layoutIfNeeded()
let btnPortal = makeButton()
btnPortal.setTitle("My Button", forState: .Normal)
btnPortal.addTarget(self, action: "gotoPushWebPortalAction", forControlEvents: .TouchUpInside)
let headerStackView = UIStackView(arrangedSubviews: [lblHeader, btnPortal, lblInfo, lblInfo2])
headerStackView.axis = .Vertical
headerStackView.alignment = .Center
headerStackView.distribution = .Fill
headerStackView.spacing = 2
headerStackView.setContentCompressionResistancePriority(1000, forAxis: .Vertical)
headerStackView.setContentHuggingPriority(10, forAxis: .Vertical)
headerStackView.setNeedsUpdateConstraints()
headerStackView.setNeedsLayout()
//headerStackView.layoutMarginsRelativeArrangement = true
return headerStackView
}
所以做出長話短說:什麼是需要調整我的stackviews,所以每個stackview,因此標籤在全尺寸光榮顯示?我試圖壓縮和擁抱一切,但它似乎沒有工作。而谷歌搜索uistackview uilabel multiline truncated似乎是一個死衚衕,也
我感謝所有幫助, 問候弗洛裏
如http://stackoverflow.com/questions/34386528/multiline-label-in-uistackview/34430212#34430212中所示,關鍵是爲您的堆棧視圖設置固定寬度,以便爲多行標籤指定一些東西遇到併成爲多線。 – GlennRay
@SpaceDog imho他們沒有很差的計劃,但他們有不同的邏輯比其他控制,需要不同的思維方式更復雜的佈局,特別是因爲他們的填充規則 –