2017-07-01 126 views
2

我正在嘗試創建一個類似於Youtube的應用程序。我在這個項目中沒有使用IB。我遇到的問題是,當句子太大而無法合併到一行時,文本會被切斷。我想顯示第一句話,而不是像Original Youtube應用程序那樣被截斷。下面給出了UILabel的代碼。對於titlelabelUILabel被截斷的文本

//top 
addConstraint(NSLayoutConstraint(item: titleLabel, attribute: .Top,  relatedBy: .Equal, toItem: thumbnailImageView, attribute: .Bottom, multiplier: 1, constant: 8)) 

    //left 
    addConstraint(NSLayoutConstraint(item: titleLabel, attribute: .Left, relatedBy: .Equal, toItem: profileImageView, attribute: .Right, multiplier: 1, constant: 8)) 
    //right 
addConstraint(NSLayoutConstraint(item: titleLabel, attribute: .Right, relatedBy: .Equal, toItem: thumbnailImageView, attribute: .Right, multiplier: 1, constant: 0)) 
    // height 
titleLabelHeightConstraint = NSLayoutConstraint(item: titleLabel, attribute: .Height, relatedBy: .Equal, toItem: self, attribute: .Height, multiplier: 0, constant: 44) 
     addConstraint(titleLabelHeightConstraint!) 

下面的圖片可以給什麼我上面的意思的想法

let titleLabel:UILabel = { 
     let label = UILabel() 
     label.text = "Linkin Park - Numb" 
     label.translatesAutoresizingMaskIntoConstraints = false 
     label.numberOfLines = 2 
     return label 
    }() 

//約束。 My App

我也張貼原始Youtube應用程序的圖像。第一句永遠不會在原來的Youtube應用中被切斷。 Youtube App

有什麼方法可以在我的應用程序中顯示文本就像Youtube一樣嗎?

+1

嘗試刪除高度約束。它會自動擴展高度。 – xmhafiz

+0

謝謝你的工作。 –

+0

有一個小問題。當我刪除高度約束時,第二條線與第一條線不一致,它稍微向右移動。你知道如何解決這個問題嗎? –

回答

1

嘗試這樣做: -

label.lineBreakMode = .ByCharWrapping 
label.numberOfLines = 0 
+0

我試過你的,但它不顯示整個句子,雖然第一行永遠不會被切斷 –

+0

嘗試此除了刪除高度限制。 –

1
Hi just remove the height constraint 
titleLabelHeightConstraint = NSLayoutConstraint(item: titleLabel, attribute: .Height, relatedBy: .Equal, toItem: self, attribute: .Height, multiplier: 0, constant: 44) 
     addConstraint(titleLabelHeightConstraint!) 

and **add the bottom constraint to the label** as in current scenario the label does't have the bottom constraint so that label does't know how much increase . 
+0

我試過你,但它變得更糟,如果我添加底部約束,因爲TitleLabel底部有另一個標籤,它具有頂部約束,所以我不需要底部約束標題標籤。 –