多种颜色NSString或NSMutableStrings不可能.所以我听说过一些关于iPad SDK 3.2(或3.2左右)NSAttributedString引入的内容,并且可以在iPhone SDK 4.0 beta版的iPhone上获得.
我想要一个有三种颜色的字符串.
我不使用3个单独的NSStrings的原因是因为三个NSAttributedString子串中的每个子串的长度经常变化,所以我更喜欢,不使用任何计算来重新定位3个单独的NSString对象.
如果可以使用NSAttributedString我如何进行以下操作 - (如果不能使用NSAttributed字符串,你会怎么做):

编辑:
请记住,@"first",@"second"并@"third"会在任何时间其他字符串替换.因此,使用硬编码的NSRange值将不起作用.
我怎么能转换NSRange到Range<String.Index>斯威夫特?
我想使用以下UITextFieldDelegate方法:
func textField(textField: UITextField!,
shouldChangeCharactersInRange range: NSRange,
replacementString string: String!) -> Bool {
textField.text.stringByReplacingCharactersInRange(???, withString: string)
Run Code Online (Sandbox Code Playgroud)

我想从匹配正则表达式模式的字符串中提取子字符串.
所以我正在寻找这样的东西:
func matchesForRegexInText(regex: String!, text: String!) -> [String] {
???
}
Run Code Online (Sandbox Code Playgroud)
所以这就是我所拥有的:
func matchesForRegexInText(regex: String!, text: String!) -> [String] {
var regex = NSRegularExpression(pattern: regex,
options: nil, error: nil)
var results = regex.matchesInString(text,
options: nil, range: NSMakeRange(0, countElements(text)))
as Array<NSTextCheckingResult>
/// ???
return ...
}
Run Code Online (Sandbox Code Playgroud)
问题是,这matchesInString提供了我的一个数组NSTextCheckingResult,其中NSTextCheckingResult.range的类型的NSRange.
NSRange是不相容的Range<String.Index>,所以它阻止我使用text.substringWithRange(...)
有没有想过如何在没有太多代码的情况下在swift中实现这个简单的事情?
NSAttributedString 对我来说真是难以捉摸.
我想设置一个UILabel具有不同大小的文本,我收集的NSAttributedString是要走的路,但我无法获得任何关于此的文档.
如果有人能用一个具体的例子来帮助我,我会很高兴.
例如,假设我想要的文字是:
(in small letters:) "Presenting The Great..."
(in huge letters:) "HULK HOGAN!"
Run Code Online (Sandbox Code Playgroud)
有人可以告诉我该怎么做吗?或者甚至是一个简单明了的参考资料,我可以为自己学习?我发誓我已经尝试通过文档来理解这一点,甚至通过Stack Overflow上的其他示例,我只是没有得到它.
是否有一个简短的方法来说"整个字符串"而不是输入:
NSMakeRange(0, myString.length)]
Run Code Online (Sandbox Code Playgroud)
这种代码中最长的一部分是最不重要的(因为我通常想在整个字符串中搜索/替换),这似乎很愚蠢......
[myString replaceOccurrencesOfString:@"replace_me"
withString:replacementString
options:NSCaseInsensitiveSearch
range:NSMakeRange(0, myString.length)];
Run Code Online (Sandbox Code Playgroud) 我正在更新swift 3中的代码.将Range转换为NSRange时出错.如何在swift 3中做到这一点?
func nsRange(_ range : Range<String.Index>) -> NSRange {
let utf16from = String.UTF16View.Index(range.lowerBound, within: utf16)
let utf16to = String.UTF16View.Index(range.upperBound, within: utf16)
return NSRange(location: utf16.startIndex.distanceTo(utf16from), length: utf16from.distanceTo(utf16to))
}
Run Code Online (Sandbox Code Playgroud) 我正在尝试添加到UITextViews的链接,所以我正在关注这篇文章中的代码.相关的Objective-C代码是
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:@"This is an example by @marcelofabri_"];
[attributedString addAttribute:NSLinkAttributeName
value:@"username://marcelofabri_"
range:[[attributedString string] rangeOfString:@"@marcelofabri_"]];
Run Code Online (Sandbox Code Playgroud)
但是当我在Swift 2中尝试这个时
var attributedString = NSMutableAttributedString(string: "This is an example by @marcelofabri_")
attributedString.addAttribute(NSLinkAttributeName, value: "username://marcelofabri_", range: attributedString.string.rangeOfString("/marcelofabri_"))
Run Code Online (Sandbox Code Playgroud)
我收到了错误
无法使用类型'(String,value:String,range:Range?)'的参数列表调用'addAttribute'
我需要做些什么才能让它发挥作用?
我试图用属性String替换子字符串.以下是我的代码.
let searchText = self.searchBar.text!
let name = item.firstName ?? ""
let idNo = "Employee Id. \(item.employeeId ?? "NA")"
if let range = name.range(of: searchText, options: String.CompareOptions.caseInsensitive, range: nil, locale: nil)
{
let attributedSubString = NSAttributedString.init(string: name.substring(with: range), attributes: [NSFontAttributeName : UIFont.boldSystemFont(ofSize: 17)])
let normalNameString = NSMutableAttributedString.init(string: name)
normalNameString.mutableString.replacingCharacters(in: range, with: attributedSubString)
cell.name.attributedText = normalNameString
}
else
{
cell.name.text = name
}
Run Code Online (Sandbox Code Playgroud)
我收到编译时错误:
"无法将'Range'类型的值(又称'Range')转换为预期的参数类型'NSRange'(又名'_NSRange')".
我应该在这里改变什么?
使用NSMutableAttributedString在UILabel上设置文本部分时遇到一些奇怪的问题。它显示了一些特定表情符号的奇异符号。这是我使用的代码和问题的屏幕截图。
guard var _comment = comment.comment ,let _username = comment.userName else { return }
var username = NSMutableAttributedString.init(string: _username)
var commentText = NSMutableAttributedString.init(string: _comment)
var commentTotal = NSMutableAttributedString.init()
commentTotal.append(username)
commentTotal.append(commentText)
self.userNameLabel.attributedText = commentTotal
Run Code Online (Sandbox Code Playgroud)
屏幕截图:
但是,如果我不使用NSMutableAttributedString就直接放置字符串,如下所示:
self.userName.text = _comment
Run Code Online (Sandbox Code Playgroud)
此输出显示正确的表情符号,没有问题。这是什么问题?有任何建议吗?

这是设置字体的代码:
if let font = UIFont.init(name: "Montserrat-Bold", size: self.userNameLabel.font.pointSize){
username.addAttribute(NSFontAttributeName, value: font, range: NSRange.init(location: 0, length: _username.count))
username.addAttribute(NSForegroundColorAttributeName, value: UIColor.init(red: 0/255, green: 0/255, blue: 0/255, alpha: 1.0), range: NSRange.init(location: 0, length: _username.count))
}
if let font = UIFont.init(name: "Montserrat-Medium", size: self.userNameLabel.font.pointSize-1){ …Run Code Online (Sandbox Code Playgroud) nsattributedstring uilabel ios nsmutableattributedstring swift
我有一个字符串,例如"ab ad adk fda kla kad ab ab kd".我想获得所有范围的ab.(这里ab出现在3个位置所以我应该得到3个范围).在正常情况下我的代码工作正常,但如果搜索文本是".",那么我得到错误的结果
do {
let regEx = try NSRegularExpression(pattern: searchText, options: NSRegularExpressionOptions.CaseInsensitive)
let matchesRanges = regEx.matchesInString(attributedText.string, options:[], range: NSMakeRange(0, attributedText.string.length))
for rng in matchesRanges {
let wordRange = rng.rangeAtIndex(0)
}
} catch {
...
}
Run Code Online (Sandbox Code Playgroud) 我有一个 NSMutatableString:
var string: String = "Due in %@ (%@) $%@.\nOverdue! Please pay now %@"
attributedText = NSMutableAttributedString(string: string, attributes: attributes)
Run Code Online (Sandbox Code Playgroud)
如何快速计算单词的长度和起始索引Overdue?
到目前为止,我已经尝试过:
let startIndex = attributedText.string.rangeOfString("Overdue")
let range = startIndex..<attributedText.string.finishIndex
// Access the substring.
let substring = value[range]
print(substring)
Run Code Online (Sandbox Code Playgroud)
但它不起作用。
我希望在Swift 2.x中执行此操作:假设我在文本字段中输入文本.- 'Apple iPhone http://www.apple.com '
我现在正在更新带有标签的UIButton - Apple iPhone.当点击按钮启动' http://www.apple.com时,我想要IBAction .
我可以设置它,但我遇到麻烦的部分是 - 我如何从文本字段解析'Apple iPhone'和' http://www.apple.com '并将它们分开以便我可以更新UIButton标签一些文本并使用URL启动Safari?更具体地说,我希望能够检测"http://"之后的任何"文本",并始终使用文本来更新标签,并使用http来启动带有URL的浏览器.谢谢回答.
如何在没有先转换为?的情况下转换Range<String.Index>为NSRangeSwift(<4)?StringNSString
我想这样做的原因是,我想设置UITextView的selectedText使用属性Range<String.Index>值.
另一种解决方案:如何设置UITextInput.selectedTextRange一个Range<String.Index>值?