ios Swift 4 标签属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46647438/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 09:34:01  来源:igfitidea点击:

Swift 4 Label attributes

iosswiftuilabelnsattributedstringswift4

提问by Blue

I'm moving from swift 3 to swift 4. I have UILabels that I am giving very specific text properties to the label. I'm getting an 'unexpectedly found nil while unwrapping optional value' error when strokeTextAttributes is being initialized. I'm totally lost to be frank.

我正在从 swift 3 转移到 swift 4。我有 UILabels,我为标签提供了非常具体的文本属性。初始化 strokeTextAttributes 时,我收到“在解开可选值时意外发现 nil”错误。坦率地说,我完全迷失了。

In swift 3 the of strokeTextAttributes was [String : Any] but swift 4 threw errors until I changed it to what it is below.

在 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)

回答by Xavier Lowmiller

@Larme's comment about the .rawValuenot being needed is correct.

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

Also, you can avoid the force cast that crashes your code using explicit typing:

此外,您可以使用显式类型避免强制转换导致代码崩溃:

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

This gets rid of the repetitive NSAttributedString.Key., too.

这也摆脱了重复NSAttributedString.Key.

回答by Krunal

In Swift 4.0+, attributed string accepts json (dictionary) with key type NSAttributedStringKeyor NSAttributedString.Key.

在 中Swift 4.0+,属性字符串接受键类型为NSAttributedStringKey或 的json(字典)NSAttributedString.Key

So you must change it from [String : Any]to

所以你必须把它从[String : Any]改为

Swift 4.1 & below -[NSAttributedStringKey : Any]&
Swift 4.2 & above -[NSAttributedString.Key : Any]

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

Swift 4.2

斯威夫特 4.2

Initialiser for AttributedStringin Swift 4.2 is changed to [NSAttributedString.Key : Any]?

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

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

Here is sample working code.

这是示例工作代码。

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

斯威夫特 4.0

Initialiser for AttributedStringin Swift 4.0 is changed to [NSAttributedStringKey : Any]?.

AttributedStringSwift 4.0 中的Initialiser更改为[NSAttributedStringKey : Any]?.

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

Here is sample working code.

这是示例工作代码。

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)

Look at this Apple Document, for more info: NSAttributedString - Creating an NSAttributedString Object

查看这个 Apple 文档,了解更多信息:NSAttributedString - 创建一个 NSAttributedString 对象

回答by Vini App

NSAttributedStringKey.strokeColor.rawValueis of type String

NSAttributedStringKey.strokeColoris of type NSAttributedStringKey

NSAttributedStringKey.strokeColor.rawValue是类型 String

NSAttributedStringKey.strokeColor是类型 NSAttributedStringKey

So its unable to convert Stringto NSAttributedStringKey. You have to use like below:

所以它无法转换StringNSAttributedStringKey. 你必须像下面这样使用:

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

回答by Azharhussain Shaikh

Swift 4 Attributed text with multiple colors

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
}
}

Now you can Execute the function something like this to use as a globally

现在您可以执行类似这样的函数以用作全局

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
}

You can use globalized function like this

您可以像这样使用全球化函数

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

Attributed text with image

带有图像的属性文本

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 
}

you can use "NSTextAttachment" with your button label like this.

您可以像这样使用带有按钮标签的“NSTextAttachment”。

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

回答by Arunabh Das

In Swift 4.x, this should look like :

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

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

回答by Priya Gupta

if you want to change particular string value so that below answer is helpful you:-

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

let subStr = "Hello" let allStr = "Hello World"

let subStr = "Hello" let 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

回答by Danut Pralea

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