2017-08-09 113 views
-1

我想在不使用2個標籤的情況下實現類似的效果。如何在swift中對UILabel的藥水進行着色3

enter image description here

如何創建一個UILabel像this.Please幫助我。

+0

搜索AttributedString,這將有助於肯定 – Vikky

+0

@Vikky yeas我知道它應該是AttributedString的東西。但是,我如何着色UILabel的藥水? – user1960169

+0

爲什麼你不能使用兩個標籤?這將是獲得均勻間距的最簡單方法。 –

回答

1

您可以使用NSMutableAttributedStringNSBackgroundColorAttributeName屬性來實現上述結果

var attributedString = NSMutableAttributedString(string:yourString)attributedString.addAttribute(NSBackgroundColorAttributeName, value: .redColor() , range: range) 
yourLabel.attributedText = attributedString 
0

爲了實現這個輸出我們使用NSAttribute

下面的代碼嘗試

//This is for setting border of UILabel 
    let labelColor = UIColor(colorLiteralRed: 255.0/255.0, green: 115.0/255.0, blue: 116.0/255.0, alpha: 1.0) 
    lblNoOfDays.layer.masksToBounds = true 
    lblNoOfDays.layer.borderWidth = 1.0 
    lblNoOfDays.layer.borderColor = labelColor.cgColor 

    //This is value we display 
    let strValueTitle = "No of Days" 
    let strValue = "04" 

    //Attribute dictionary we use 
    //NSFontAttributeName:- sets font and it's size 
    //NSForegroundColorAttributeName:- sets text colour 
    //NSBackgroundColorAttributeName:- sets background color 
    let attributeTitle = [NSFontAttributeName: UIFont.systemFont(ofSize: 11.0), NSForegroundColorAttributeName: labelColor, NSBackgroundColorAttributeName: UIColor.clear] 
    let attributeVal = [NSFontAttributeName: UIFont.systemFont(ofSize: 12.0), NSForegroundColorAttributeName: UIColor.white, NSBackgroundColorAttributeName: labelColor] 

    //Implement attributes to string 
    let attributTitleString = NSMutableAttributedString(string: strValueTitle, attributes: attributeTitle) 
    let attributeValue = NSAttributedString(string: strValue, attributes: attributeVal) 

    //Append attributed string 
    attributTitleString.append(attributeValue) 

    //Assign attributed string to label 
    lblNoOfDays.attributedText = attributTitleString 
    lblNoOfDays.sizeToFit() 

您需要在UILabel中設置填充以獲得所需的輸出。

相關問題