我有一段文字,上面写着“Hello world. The world is so beautiful.”我想将其更改为“你好世界。世界是如此美丽。”
我试过下面的代码,但它只改变了第一个词。
let string : NSString = "Hello world. The world is so beautiful."
let attributedString = NSMutableAttributedString(string: string! as String, attributes: [NSFontAttributeName:UIFont.systemFont(ofSize: 17.0)])
let italicFontAttribute = [NSFontAttributeName: UIFont.italicSystemFont(ofSize: 17.0)]
attributedString.addAttributes(italicFontAttribute, range: (string!.range(of: "world")))
最佳答案
添加到其他解决方案但搜索特定术语并替换所有出现的解决方案可以帮助您为此创建通用方法:
var sampleString : String = "Hello world. The world is so beautiful."
let searchTerm : String = "world"
var searchRange : NSRange = NSMakeRange(0, sampleString.characters.count)
var positionRange : NSRange = ((sampleString as NSString).substring(with: searchRange) as NSString).range(of: searchTerm)
var actualRange : NSRange = positionRange
var attributedString : NSMutableAttributedString = NSMutableAttributedString(string: sampleString)
while (positionRange.location != NSNotFound)
{
// Update attributed string
actualRange.location = searchRange.location + positionRange.location
attributedString.addAttributes([ NSFontAttributeName : UIFont(name: "Helvetica-Italic", size: CGFloat(22)) ], range: actualRange)
// Proceed to the next position
searchRange.location += positionRange.location + searchTerm.characters.count
searchRange.length = sampleString.characters.count - searchRange.location
positionRange = ((sampleString as NSString).substring(with: searchRange) as NSString).range(of: searchTerm)
}
关于ios - 如何在 Swift 的字符串中将某个单词(多次出现)设为斜体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43177259/