ios - 如何在 Swift 的字符串中将某个单词(多次出现)设为斜体?

标签 ios swift

我有一段文字,上面写着“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/

相关文章:

ios - 在看到 View 之前添加约束?

ios - 如果语言是阿拉伯语,RangeSeekSlider 应从右向左开始

ios - iOS 5 中的 View Controller 有什么方法可以指定要在导航堆栈推送上的后退按钮中使用的图像吗?

ios - 如何在swift中将json对象一个一个写入json对象

html - iOS 设备上的 MP4 浏览器内视频播放间歇性中断

iphone - NSFetchedResultsChangeUpdate 更改类型何时发生?

swift - NSNumber & NSDate (swift 3)

ios - 具有自定义层的 UIButton 子类不会完全填充相邻 View 的空间

ios - Reachability reachable和unreachableBlock被多次调用?

javascript - 如何使用 ionic (v1) 框架呈现弹出式 viewController?