如何在快速3中为UILabel配色药水

时间:2017-08-09 04:19:43

标签: ios swift3 uilabel

我希望在不使用2个标签的情况下实现这样的目标。

enter image description here

如何创建像这样的UILabel。请帮助我。

1 个答案:

答案 0 :(得分:0)

为了实现此输出,我们使用NSAttribute class

尝试以下代码

    //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中设置填充以获得所需的输出。