我遇到的问题是我希望能够在TextView中更改某些文本的textColor。我正在使用连接字符串,只想要我附加到TextView文本中的字符串。似乎我想要使用的是NSMutableAttributedString
,但我找不到任何有关如何在Swift中使用它的资源。到目前为止我所拥有的是这样的:
let string = "A \(stringOne) with \(stringTwo)"
var attributedString = NSMutableAttributedString(string: string)
textView.attributedText = attributedString
从这里我知道我需要找到需要更改textColor的单词范围,然后将它们添加到属性字符串中。我需要知道的是如何从attributionString中找到正确的字符串,然后更改它们的textColor。
由于我的评分太低,我无法回答我自己的问题,但这是我找到的答案
我通过翻译来自
的翻译来找到我自己的答案Change attributes of substrings in a NSAttributedString
以下是Swift中的实现示例:
let string = "A \(stringOne) and \(stringTwo)"
var attributedString = NSMutableAttributedString(string:string)
let stringOneRegex = NSRegularExpression(pattern: nameString, options: nil, error: nil)
let stringOneMatches = stringOneRegex.matchesInString(longString, options: nil, range: NSMakeRange(0, attributedString.length))
for stringOneMatch in stringOneMatches {
let wordRange = stringOneMatch.rangeAtIndex(0)
attributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor.nameColor(), range: wordRange)
}
textView.attributedText = attributedString
由于我想要更改多个字符串的textColor,我将创建一个帮助函数来处理它,但这适用于更改textColor。
答案 0 :(得分:94)
我看到你在某种程度上回答了这个问题,但是在不使用正则表达式回答标题问题的情况下提供了一种更简洁的方式:
要更改文本长度的颜色,您需要知道字符串中有颜色字符的开始和结束索引,例如
var main_string = "Hello World"
var string_to_color = "World"
var range = (main_string as NSString).rangeOfString(string_to_color)
然后转换为属性字符串并使用'添加属性'使用NSForegroundColorAttributeName:
var attributedString = NSMutableAttributedString(string:main_string)
attributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor() , range: range)
中找到可以设置的其他标准属性的列表
答案 1 :(得分:72)
SWIFT 5
let main_string = "Hello World"
let string_to_color = "World"
let range = (main_string as NSString).range(of: string_to_color)
let attribute = NSMutableAttributedString.init(string: main_string)
attribute.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.red , range: range)
txtfield1 = UITextField.init(frame:CGRect(x:10 , y:20 ,width:100 , height:100))
txtfield1.attributedText = attribute
SWIFT 4.2
let txtfield1 :UITextField!
let main_string = "Hello World"
let string_to_color = "World"
let range = (main_string as NSString).range(of: string_to_color)
let attribute = NSMutableAttributedString.init(string: main_string)
attribute.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.red , range: range)
txtfield1 = UITextField.init(frame:CGRect(x:10 , y:20 ,width:100 , height:100))
txtfield1.attributedText = attribute
答案 2 :(得分:41)
Swift 2.1更新:
let text = "We tried to make this app as most intuitive as possible for you. If you have any questions don't hesitate to ask us. For a detailed manual just click here."
let linkTextWithColor = "click here"
let range = (text as NSString).rangeOfString(linkTextWithColor)
let attributedString = NSMutableAttributedString(string:text)
attributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor() , range: range)
self.helpText.attributedText = attributedString
self.helpText
是UILabel
出口。
答案 3 :(得分:10)
以前的帖子已经给出了答案,但我有不同的方式来做这个
Swift 3x:
var myMutableString = NSMutableAttributedString()
myMutableString = NSMutableAttributedString(string: "Your full label textString")
myMutableString.setAttributes([NSFontAttributeName : UIFont(name: "HelveticaNeue-Light", size: CGFloat(17.0))!
, NSForegroundColorAttributeName : UIColor(red: 232 / 255.0, green: 117 / 255.0, blue: 40 / 255.0, alpha: 1.0)], range: NSRange(location:12,length:8)) // What ever range you want to give
yourLabel.attributedText = myMutableString
希望这有助于任何人!
答案 4 :(得分:7)
static func createAttributedString(fullString: String, fullStringColor: UIColor, subString: String, subStringColor: UIColor) -> NSMutableAttributedString
{
let range = (fullString as NSString).rangeOfString(subString)
let attributedString = NSMutableAttributedString(string:fullString)
attributedString.addAttribute(NSForegroundColorAttributeName, value: fullStringColor, range: NSRange(location: 0, length: fullString.characters.count))
attributedString.addAttribute(NSForegroundColorAttributeName, value: subStringColor, range: range)
return attributedString
}
答案 5 :(得分:5)
NSAttributedStringKey.foregroundColor
例如,如果您想在NavBar中更改字体:
self.navigationController?.navigationBar.titleTextAttributes = [ NSAttributedStringKey.font: UIFont.systemFont(ofSize: 22), NSAttributedStringKey.foregroundColor: UIColor.white]
答案 6 :(得分:5)
您可以使用此扩展名 我通过
进行了测试import Foundation
import UIKit
extension NSMutableAttributedString {
convenience init (fullString: String, fullStringColor: UIColor, subString: String, subStringColor: UIColor) {
let rangeOfSubString = (fullString as NSString).range(of: subString)
let rangeOfFullString = NSRange(location: 0, length: fullString.count)//fullString.range(of: fullString)
let attributedString = NSMutableAttributedString(string:fullString)
attributedString.addAttribute(NSAttributedStringKey.foregroundColor, value: fullStringColor, range: rangeOfFullString)
attributedString.addAttribute(NSAttributedStringKey.foregroundColor, value: subStringColor, range: rangeOfSubString)
self.init(attributedString: attributedString)
}
}
答案 7 :(得分:3)
Swift 2.2
var myMutableString = NSMutableAttributedString()
myMutableString = NSMutableAttributedString(string: "1234567890", attributes: [NSFontAttributeName:UIFont(name: kDefaultFontName, size: 14.0)!])
myMutableString.addAttribute(NSForegroundColorAttributeName, value: UIColor(red: 0.0/255.0, green: 125.0/255.0, blue: 179.0/255.0, alpha: 1.0), range: NSRange(location:0,length:5))
self.lblPhone.attributedText = myMutableString
答案 8 :(得分:3)
根据我创建字符串扩展名之前的答案
=FILTER({"a";"b";"c";"d"},{"a";"b";"c";"d"}<>A1)
您可以将文本的属性传递给方法
像这样打电话
extension String {
func highlightWordsIn(highlightedWords: String, attributes: [[NSAttributedStringKey: Any]]) -> NSMutableAttributedString {
let range = (self as NSString).range(of: highlightedWords)
let result = NSMutableAttributedString(string: self)
for attribute in attributes {
result.addAttributes(attribute, range: range)
}
return result
}
}
答案 9 :(得分:3)
在扩展String时使用NSMutableAttributedString的非常简单的方法。 Swift 4.2中的解决方案,但我认为在其他Swift版本中也很容易处理。这也可以用于给整个字符串中的多个单词上色。
为扩展名添加新文件,文件->新建->新文件,名称为ex。 “ NSAttributedString + TextColouring”并添加代码
import UIKit
extension String {
func attributedStringWithColor(_ strings: [String], color: UIColor, characterSpacing: UInt? = nil) -> NSAttributedString {
let attributedString = NSMutableAttributedString(string: self)
for string in strings {
let range = (self as NSString).range(of: string)
attributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: color, range: range)
}
guard let characterSpacing = characterSpacing else {return attributedString}
attributedString.addAttribute(NSAttributedString.Key.kern, value: characterSpacing, range: NSRange(location: 0, length: attributedString.length))
return attributedString
}
}
现在,您可以在所需的任何视图控制器上全局使用
:let attributedWithTextColor: NSAttributedString = "Doc, welcome back :)".attributedStringWithColor(["Doc", "back"], color: UIColor.black)
myLabel.attributedText = attributedWithTextColor
答案 10 :(得分:2)
此扩展在使用已设置的默认颜色配置标签文本时效果很好。
name: Build and Deploy
on:
push:
branches:
- master
jobs:
build:
name: Build Website
runs-on: ubuntu-latest
steps:
- name: Checkout Repo
uses: actions/checkout@master
- name: Install Website Dependencies
run: cd website && npm install
- name: Audit & Fund Website Dependencies
run: cd website && npm audit fix && npm fund
- name: Build Website
run: cd website && CI=false npm run build <<-------------fail at this
deploy:
name: Deploy Website to Live
needs: build
runs-on: ubuntu-latest
steps:
- name: Deploy to Live Domain
uses: w9jds/firebase-action@master
with:
args: deploy --only hosting:dev
env:
FIREBASE_TOKEN: ${{ secrets.FIREBASE_TOKEN }}
例如
public extension String {
func setColor(_ color: UIColor, ofSubstring substring: String) -> NSMutableAttributedString {
let range = (self as NSString).range(of: substring)
let attributedString = NSMutableAttributedString(string: self)
attributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: color, range: range)
return attributedString
}
}
答案 11 :(得分:2)
使用此简单功能,您可以分配文本并突出显示所选单词。
您还可以将 UITextView 更改为 UILabel ,等等。
func highlightBoldWordAtLabel(textViewTotransform: UITextView, completeText: String, wordToBold: String){
textViewToTransform.text = completeText
let range = (completeText as NSString).range(of: wordToBold)
let attribute = NSMutableAttributedString.init(string: completeText)
attribute.addAttribute(NSAttributedString.Key.font, value: UIFont.boldSystemFont(ofSize: 16), range: range)
attribute.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.black , range: range)
textViewToTransform.attributedText = attribute
}
答案 12 :(得分:2)
Swift 4.1
我已经改变了 在Swift 3中
let str = "Welcome "
let welcomeAttribute = [ NSForegroundColorAttributeName: UIColor.blue()]
let welcomeAttrString = NSMutableAttributedString(string: str, attributes: welcomeAttribute)
这在Swift 4.0中
let str = "Welcome "
let welcomeAttribute = [ NSAttributedStringKey.foregroundColor: UIColor.blue()]
let welcomeAttrString = NSMutableAttributedString(string: str, attributes: welcomeAttribute)
到 Swift 4.1
let str = "Welcome "
let welcomeAttribute = [ NSAttributedStringKey(rawValue: NSForegroundColorAttributeName): UIColor.blue()]
let welcomeAttrString = NSMutableAttributedString(string: str, attributes: welcomeAttribute)
工作正常
答案 13 :(得分:1)
对于正在寻找“ 将特定颜色应用于文本中的多个单词 ”的每个人,我们都可以使用 NSRegularExpression
func highlight(matchingText: String, in text: String) {
let attributedString = NSMutableAttributedString(string: text)
if let regularExpression = try? NSRegularExpression(pattern: "\(matchingText)", options: .caseInsensitive) {
let matchedResults = regularExpression.matches(in: text, options: [], range: NSRange(location: 0, length: attributedString.length))
for matched in matchedResults {
attributedString.addAttributes([NSAttributedStringKey.backgroundColor : UIColor.yellow], range: matched.range)
}
yourLabel.attributedText = attributedString
}
}
答案 14 :(得分:1)
迅速4.2
let textString = "Hello world"
let range = (textString as NSString).range(of: "world")
let attributedString = NSMutableAttributedString(string: textString)
attributedString.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.red, range: range)
self.textUIlable.attributedText = attributedString
答案 15 :(得分:1)
这可能对您有用
let main_string = " User not found,Want to review ? Click here"
let string_to_color = "Click here"
let range = (main_string as NSString).range(of: string_to_color)
let attribute = NSMutableAttributedString.init(string: main_string)
attribute.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.blue , range: range)
lblClickHere.attributedText = attribute
答案 16 :(得分:1)
答案 17 :(得分:1)
您可以使用简单的扩展名
extension String{
func attributedString(subStr: String) -> NSMutableAttributedString{
let range = (self as NSString).range(of: subStr)
let attributedString = NSMutableAttributedString(string:self)
attributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.red , range: range)
return attributedString
}
}
myLable.attributedText = fullStr.attributedString(subStr: strToChange)
答案 18 :(得分:0)
超级简单的方法。
let text = "This is a colorful attributed string"
let attributedText =
NSMutableAttributedString.getAttributedString(fromString: text)
attributedText.apply(color: .red, subString: "This")
//Apply yellow color on range
attributedText.apply(color: .yellow, onRange: NSMakeRange(5, 4))
有关更多详细信息,请单击此处: https://github.com/iOSTechHub/AttributedString
答案 19 :(得分:0)
答案 20 :(得分:0)
您可以使用此方法。我在通用工具类中实现了此方法以进行全局访问。
func attributedString(with highlightString: String, normalString: String, highlightColor: UIColor) -> NSMutableAttributedString {
let attributes = [NSAttributedString.Key.foregroundColor: highlightColor]
let attributedString = NSMutableAttributedString(string: highlightString, attributes: attributes)
attributedString.append(NSAttributedString(string: normalString))
return attributedString
}
答案 21 :(得分:0)
您需要更改textview参数,而不是属性字符串的参数
textView.linkTextAttributes = [
NSAttributedString.Key.foregroundColor: UIColor.red,
NSAttributedString.Key.underlineColor: UIColor.red,
NSAttributedString.Key.underlineStyle: NSUnderlineStyle.single.rawValue
]
答案 22 :(得分:0)
请检查可可足纲Prestyler:
private void getValues()
{
Log.v(TAG, "getValues(): init");
EditText nameET = findViewById(R.id.nameET);
EditText descriptionET = findViewById(R.id.descriptionET);
EditText priceET = findViewById(R.id.priceET);
EditText categoryET = findViewById(R.id.categoryET);
CheckBox stateCHB = findViewById(R.id.checkBox);
String name = nameET.getText().toString();
String description = descriptionET.getText().toString();
Float price = Float.valueOf(priceET.getText().toString());
String category = categoryET.getText().toString();
boolean state;
if (stateCHB.isChecked())
{
state = true;
}
else
{
state = false;
}
sendDataToServer(name, description, price, state, category, imagePath);
Log.v(TAG, "getValues(): end");
}
答案 23 :(得分:0)
extension String{
// to make text field mandatory * looks
mutating func markAsMandatoryField()-> NSAttributedString{
let main_string = self
let string_to_color = "*"
let range = (main_string as NSString).range(of: string_to_color)
print("The rang = \(range)")
let attribute = NSMutableAttributedString.init(string: main_string)
attribute.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.rgbColor(red: 255.0, green: 0.0, blue: 23.0) , range: range)
return attribute
}
}
使用 EmailLbl.attributedText = EmailLbl.text!.markAsMandatoryField()
答案 24 :(得分:0)
如果您使用的是Swift 3x和UITextView,那么NSForegroundColorAttributeName可能无法正常工作(无论我采用何种方法,它都不适合我。)
所以,经过一番挖掘,我找到了解决方案。
//Get the textView somehow
let textView = UITextView()
//Set the attributed string with links to it
textView.attributedString = attributedString
//Set the tint color. It will apply to the link only
textView.tintColor = UIColor.red