I am trying to make a simple Coffee Calculator. I need to display the amount of coffee in grams. The "g" symbol for grams needs to be attached to my UILabel that I am using to display the amount. The numbers in the UILabel are changing dynamically with user input just fine, but I need to add a lower case "g" on the end of the string that is formatted differently from the updating numbers. The "g" needs to be attached to the numbers so that as the number size and position changes, the "g" "moves" with the numbers. I'm sure this problem has been solved before so a link in the right direction would be helpful as I've googled my little heart out.
I've searched through the documentation for an attributed string and I even downloded an "Attributed String Creator" from the app store, but the resulting code is in Objective-C and I am using Swift. What would be awesome, and probably helpful to other developers learning this language, is a clear example of creating a custom font with custom attributes using an attributed string in Swift. The documentation for this is very confusing as there is not a very clear path on how to do so. My plan is to create the attributed string and add it to the end of my coffeeAmount string.
var coffeeAmount: String = calculatedCoffee + attributedText
其中calculatedCoffee是一个Int转换为字符串和“attributedText”是小写的“g”与自定义字体,我试图创建。也许我做错了。任何帮助都是感激的!
extension String {
//MARK: Getting customized string
struct StringAttribute {
var fontName = "HelveticaNeue-Bold"
var fontSize: CGFloat?
var initialIndexOftheText = 0
var lastIndexOftheText: Int?
var textColor: UIColor = .black
var backGroundColor: UIColor = .clear
var underLineStyle: NSUnderlineStyle = .styleNone
var textShadow: TextShadow = TextShadow()
var fontOfText: UIFont {
if let font = UIFont(name: fontName, size: fontSize!) {
return font
} else {
return UIFont(name: "HelveticaNeue-Bold", size: fontSize!)!
}
}
struct TextShadow {
var shadowBlurRadius = 0
var shadowOffsetSize = CGSize(width: 0, height: 0)
var shadowColor: UIColor = .clear
}
}
func getFontifiedText(partOfTheStringNeedToConvert partTexts: [StringAttribute]) -> NSAttributedString {
let fontChangedtext = NSMutableAttributedString(string: self, attributes: [NSFontAttributeName: UIFont(name: "HelveticaNeue-Bold", size: (partTexts.first?.fontSize)!)!])
for eachPartText in partTexts {
let lastIndex = eachPartText.lastIndexOftheText ?? self.count
let attrs = [NSFontAttributeName : eachPartText.fontOfText, NSForegroundColorAttributeName: eachPartText.textColor, NSBackgroundColorAttributeName: eachPartText.backGroundColor, NSUnderlineStyleAttributeName: eachPartText.underLineStyle, NSShadowAttributeName: eachPartText.textShadow ] as [String : Any]
let range = NSRange(location: eachPartText.initialIndexOftheText, length: lastIndex - eachPartText.initialIndexOftheText)
fontChangedtext.addAttributes(attrs, range: range)
}
return fontChangedtext
}
}
//像下面这样使用它
let someAttributedText = "Some Text".getFontifiedText(partOfTheStringNeedToConvert: <#T##[String.StringAttribute]#>)
Objective-C 2.0示例:
myUILabel.text = @"€ 60,00";
NSMutableAttributedString *amountText = [[NSMutableAttributedString alloc] initWithString:myUILabel.text];
//Add attributes you are looking for
NSDictionary *dictionaryOfAttributes = [NSDictionary dictionaryWithObjectsAndKeys:
[UIFont systemFontOfSize:12],NSFontAttributeName,
[UIColor grayColor],NSForegroundColorAttributeName,
nil];
//Will gray color and resize the € symbol
[amountText setAttributes:dictionaryOfAttributes range:NSMakeRange(0, 1)];
myUILabel.attributedText = amountText;
在iOS上处理attributedstring的最好方法是使用接口构建器中内置的attributedtext编辑器,避免在源文件中不必要的硬编码NSAtrributedStringKeys。
你可以使用这个扩展在运行时动态替换占位符:
extension NSAttributedString {
func replacing(placeholder:String, with valueString:String) -> NSAttributedString {
if let range = self.string.range(of:placeholder) {
let nsRange = NSRange(range,in:valueString)
let mutableText = NSMutableAttributedString(attributedString: self)
mutableText.replaceCharacters(in: nsRange, with: valueString)
return mutableText as NSAttributedString
}
return self
}
}
添加带有带属性文本的故事板标签,如下所示。
然后你只需在你需要的时候更新这个值,就像这样:
label.attributedText = initalAttributedString.replacing(placeholder: "<price>", with: newValue)
确保将原始值保存到initalAttributedString中。
你可以通过阅读这篇文章来更好地理解这种方法:
https://medium.com/mobile-appetite/text-attributes-on-ios-the-effortless-approach-ff086588173e