Swift 4 Label属性

时间:2017-10-09 13:16:06

标签: ios swift uilabel nsattributedstring swift4

我从swift 3移动到swift 4.我有UILabels,我给标签提供了非常具体的文本属性。在解开可选值时,我意外地发现了一个nil。初始化strokeTextAttributes时出错。我坦率地完全迷失了。

在swift 3中,strokeTextAttributes是[String:Any],但swift 4引发了错误,直到我将其更改为下面的内容。

let strokeTextAttributes = [
    NSAttributedStringKey.strokeColor.rawValue : UIColor.black,
    NSAttributedStringKey.foregroundColor : UIColor.white,
    NSAttributedStringKey.strokeWidth : -2.0,
    NSAttributedStringKey.font : UIFont.boldSystemFont(ofSize: 18)
    ] as! [NSAttributedStringKey : Any]


chevronRightLabel.attributedText = NSMutableAttributedString(string: "0", attributes: strokeTextAttributes)

7 个答案:

答案 0 :(得分:28)

@ Larme关于不需要.rawValue的评论是正确的。

此外,您可以使用显式输入来避免强制转换代码:

let strokeTextAttributes: [NSAttributedString.Key: Any] = [
    .strokeColor : UIColor.black,
    .foregroundColor : UIColor.white,
    .strokeWidth : -2.0,
    .font : UIFont.boldSystemFont(ofSize: 18)
]

这也消除了重复的NSAttributedString.Key.

答案 1 :(得分:14)

Swift 4.0+中,属性字符串接受密钥类型为NSAttributedStringKeyNSAttributedString.Key的json(字典)。

因此,您必须将其从[String : Any]更改为

Swift 4.1&下面 - [NSAttributedStringKey : Any]&
Swift 4.2&上面 - [NSAttributedString.Key : Any]

Swift 4.2

Swift 4.2中AttributedString的初始化程序更改为[NSAttributedString.Key : Any]?

public init(string str: String, attributes attrs: [NSAttributedString.Key : Any]? = nil)

以下是示例工作代码。

let label = UILabel()
let labelText = "String Text"

let strokeTextAttributes = [
     NSAttributedString.Key.strokeColor : UIColor.black,
     NSAttributedString.Key.foregroundColor : UIColor.white,
     NSAttributedString.Key.strokeWidth : -2.0,
     NSAttributedString.Key.font : UIFont.boldSystemFont(ofSize: 18)
   ] as [NSAttributedString.Key : Any]

label.attributedText = NSAttributedString(string: labelText, attributes: strokeTextAttributes)

Swift 4.0

Swift 4.0中AttributedString的初始化程序更改为[NSAttributedStringKey : Any]?

public init(string str: String, attributes attrs: [NSAttributedStringKey : Any]? = nil)

以下是示例工作代码。

let label = UILabel()
let labelText = "String Text"

let strokeTextAttributes = [
     NSAttributedStringKey.strokeColor : UIColor.black,
     NSAttributedStringKey.foregroundColor : UIColor.white,
     NSAttributedStringKey.strokeWidth : -2.0,
     NSAttributedStringKey.font : UIFont.boldSystemFont(ofSize: 18)
   ] as [NSAttributedStringKey : Any]

label.attributedText = NSAttributedString(string: labelText, attributes: strokeTextAttributes)

请查看此Apple文档,了解更多信息:NSAttributedString - Creating an NSAttributedString Object

答案 2 :(得分:1)

  

NSAttributedStringKey.strokeColor.rawValue的类型为String

     

NSAttributedStringKey.strokeColor的类型为NSAttributedStringKey

因此无法将String转换为NSAttributedStringKey。 你必须使用如下:

let strokeTextAttributes: [NSAttributedStringKey : Any] = [
    NSAttributedStringKey.strokeColor : UIColor.black,
    NSAttributedStringKey.foregroundColor : UIColor.white,
    NSAttributedStringKey.strokeWidth : -2.0,
    NSAttributedStringKey.font : UIFont.boldSystemFont(ofSize: 18)
]

答案 3 :(得分:0)

Swift 4归因于多种颜色的文字

extension NSMutableAttributedString 
{
@discardableResult func DustyOrange(_ text: String, Fontsize : CGFloat) -> NSMutableAttributedString 
{
    let attrs: [NSAttributedStringKey: Any] = [.font: UIFont(name: "SFUIDisplay-Regular", size: Fontsize)!, NSAttributedStringKey.foregroundColor: UIColor(red: 242.0/255.0, green: 97.0/255.0, blue: 0.0/255.0, alpha: 1.0) ]
    let boldString = NSMutableAttributedString(string:text, attributes: attrs)
    append(boldString)
    return self
}
@discardableResult func WarmGrey(_ text: String, Fontsize : CGFloat) -> NSMutableAttributedString {
    let attrs: [NSAttributedStringKey: Any] = [.font: UIFont(name: "SFUIDisplay-Regular", size: Fontsize)!, NSAttributedStringKey.foregroundColor: UIColor(red: 152.0/255.0, green: 152.0/255.0, blue: 152.0/255.0, alpha: 1.0) ]
    let boldString = NSMutableAttributedString(string:text, attributes: attrs)
    append(boldString)
    return self
}
}

现在您可以执行类似这样的功能作为全局

func FormattedString(Orange : String, WarmGrey : String ,fontsize : CGFloat) -> NSMutableAttributedString 
{
   let paragraphStyle = NSMutableParagraphStyle()
   paragraphStyle.alignment = .left
   paragraphStyle.lineSpacing = 1
   paragraphStyle.paragraphSpacing = 1
   let formattedString = NSMutableAttributedString()
   formattedString
    .DustyOrange(Orange, Fontsize: fontsize)
    .WarmGrey(WarmGrey, Fontsize: fontsize )
  formattedString.addAttributes([NSAttributedStringKey.paragraphStyle: paragraphStyle], range: NSRange(location: 0, length: formattedString.length))
   return formattedString
}

您可以使用像这样的全球化功能

 yourLabelName.attributedText = FormattedString(Orange: "String with orange color", WarmGrey: " String with warm grey color.", fontsize: 11.5)

带图片的归属文字

func AttributedTextwithImgaeSuffix(AttributeImage : UIImage , AttributedText : String , buttonBound : UIButton) -> NSMutableAttributedString 
 {
   let fullString = NSMutableAttributedString(string: AttributedText + "  ")
   let image1Attachment = NSTextAttachment()
   image1Attachment.bounds = CGRect(x: 0, y: ((buttonBound.titleLabel?.font.capHeight)! - 
  AttributeImage.size.height).rounded() / 2, width: 
  AttributeImage.size.width, height: AttributeImage.size.height)
  image1Attachment.image = AttributeImage
  let image1String = NSAttributedString(attachment: image1Attachment)
  fullString.append(image1String)
  fullString.append(NSAttributedString(string: ""))
  return fullString 
}

您可以将“NSTextAttachment”与您的按钮标签一起使用。

   yourUIButton.setAttributedTitle(AttributedTextwithImgaeSuffix(AttributeImage: desiredImage, AttributedText: "desired UIButton title", buttonBound: yourUIButton), for: .normal)

答案 4 :(得分:0)

在Swift 4.x中,这应该是:

        let strokeTextAttributes: [NSAttributedStringKey: Any] = [
        NSStrokeColorAttributeName: UIColor.black,
        NSForegroundColorAttributeName : UIColor.white,
        NSStrokeWidthAttributeName : -2.0,
        NSFontAttributeName : UIFont.boldSystemFont(ofSize: 18)
    ]

答案 5 :(得分:0)

如果您想更改特定的字符串值,以便以下答案对您有所帮助:-

let subStr =“你好”  让allStr =“ Hello World”

    let newStr = NSMutableAttributedString(string: allStr)
    newStr.addAttribute(kCTFontAttributeName as NSAttributedStringKey, value:  UIFont.init(customFont: .MyriadPro_R, withSize: 18)!, range: (allStr as NSString).range(of: subStr))
    newStr.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.PrimaryColor, range: (allStr as NSString).range(of: subStr))
    self.stateLbl.attributedText = newStr

答案 6 :(得分:0)

let text = systolicString + " / " + diastolicString

let newStr = NSMutableAttributedString(string: text)
// I have static ranges, but you can also extract them dynamically
let systolicRange = NSRange(location: 0, length: 2)
let backslashRange = NSRange(location: 3, length: 1)
let diastolicRange = NSRange(location: 5, length: 2)

newStr.addAttribute(NSAttributedStringKey.font, value:  UIFont.ubuntuRegular(28), range: systolicRange)
newStr.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor(hexString: "042f57"), range: systolicRange)

newStr.addAttribute(NSAttributedStringKey.font, value:  UIFont.ubuntuLight(23), range: backslashRange)
newStr.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor(hexString: "6485a3"), range: backslashRange)

newStr.addAttribute(NSAttributedStringKey.font, value:  UIFont.ubuntuRegular(18), range: diastolicRange)
newStr.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor(hexString: "042f57"), range: diastolicRange)
// my UILabel
valueLabel.attributedText = newStr