使文本视图响应用户键入的文本
Making a text view respond to text typed by the user
我的应用程序中有一个文本视图,允许用户在其中键入任何内容。我希望文本视图在输入时检测到一些单词并改变它们的颜色。
例如,如果用户输入-"My favourite colour is red",那么我希望单词'red'得到文本颜色'red'。但是,thus 应该在句子中输入 red 之后立即发生。我应该如何实施?
你必须使用 attributedText
在 UITextView 委托方法中
- (void)textViewDidChange:(UITextView *)textView
这将解决您的问题。
我认为你应该做的是这个(如果我错了请纠正我,因为我没有 Xcode 在这台计算机上进行测试,但这应该可以工作)。如果这不起作用,请执行 Fawad Masud 并将其添加到视图中并加载...
yourTextView.addTarget(self, action: "textViewDidChange:",forControlEvents: UIControlEvents.EditingChanged)
override func viewDidLoad() {
super.viewDidLoad()
yourTextView.delegate = self //Basically makes the function below applicable to this textview
}
func textViewDidChange(textView: UITextView) { //Every time text changes this code is run
var textViewText = yourTextView.text as NSString!
if textViewText.containsString("red") {
textViewText.textColor = UIColor.redColor()
}
}
textField.addTarget(self, action: "textFieldDidChange:",forControlEvents: UIControlEvents.EditingChanged)
func textFieldDidChange(textField: UITextField) {
//your code
var main_string = textField.text
var string_to_color = "red"
var range = (main_string as NSString).rangeOfString(string_to_color)
var attributedString = NSMutableAttributedString(string:main_string)
attributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor() , range: range)
}
你需要三样东西:
在界面生成器中,您需要使用其中一种委托方法。我认为 "editingChanged" 是这里最好的。从带有 "ctrl" 的文本字段拖动到您的文档。
您需要一种方法来遍历文本字段中的字符串并检测单词。
componentsSeparatedByCharactersInSet
您需要一种为句子中的单词设置样式的方法。
NSMutableAttributedString
也很有趣:
部分代码(扔在操场上):
这会找到所有要更改的词,但会删除分隔符。需要做更多工作才能完成代码。
var strSeperator : NSCharacterSet = NSCharacterSet(charactersInString: ",.:;?! ")
var strArray = str.componentsSeparatedByCharactersInSet(strSeperator)
var styledText = NSMutableAttributedString()
for i in 0..<strArray.count {
let currentWord = strArray[i]
var currentBoolFoundInControl : Bool = false
for iB in 0..<colorTheseStrings.count {
let controlWord = colorTheseStrings[iB]
if controlWord == currentWord {
currentBoolFoundInControl = true
// add to mutable attributed string in a color
}
}
var attrString1 = NSMutableAttributedString(string: "\(strArray[i]) ")
if currentBoolFoundInControl == true {
var range = (strArray[i] as NSString).rangeOfString(strArray[i])
if strArray[i] == "red" {
attrString1.addAttribute(NSForegroundColorAttributeName, value: UIColor(red: 0.5, green: 0.0, blue: 0.0, alpha: 1.0), range: range)
} else if strArray[i] == "blue" {
attrString1.addAttribute(NSForegroundColorAttributeName, value: UIColor(red: 0.0, green: 0.0, blue: 0.5, alpha: 1.0), range: range)
}
}
styledText.appendAttributedString(attrString1)
}
myTextField.attributedText = styledText
还有一种方法:
我觉得这种方式是最稳健最酷最高效的。
代码可以稍微清理一下,可以使用更多 style/flair。这对于 "sky blue" 之类的东西确实有问题,因为它会首先找到 "blue" 并替换它。但我不得不留下一些改进的余地。 ;)
我情不自禁,所以我解决了最后一个问题。
再一次,我修复了,我的修复。现在效率更高,实际上更正了。
第一部分是 HighLighter class,将其放在单独的文档中。
// text hightlighter
class SyntaxGroup {
var wordCollection : [String] = []
var type : String = ""
var color : UIColor = UIColor(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
init(wordCollection_I : [String], type_I : String, color_I: UIColor) {
wordCollection = wordCollection_I
type = type_I
color = color_I
}
}
class SyntaxDictionairy {
var collections : [SyntaxGroup] = []
}
class SyntaxRange {
var range : NSRange
var color : UIColor
init (color_I : UIColor, range_I : NSRange) {
color = color_I
range = range_I
}
}
class HighLighter {
var ranges : [SyntaxRange] = []
var baseString : NSMutableString = NSMutableString()
var highlightedString : NSMutableAttributedString = NSMutableAttributedString()
var syntaxDictionairy : SyntaxDictionairy
init (syntaxDictionairy_I : SyntaxDictionairy) {
syntaxDictionairy = syntaxDictionairy_I
}
func run(string : String?, completion: (finished: Bool) -> Void) {
ranges = [] // reset the ranges, else it crashes when you change a previous part of the text
highlightedString = NSMutableAttributedString() // make sure all strings start fresh
baseString = NSMutableString() // make sure all strings start fresh
// multi threading to prevent locking up the interface with large libraries.
let qualityOfServiceClass = QOS_CLASS_DEFAULT
let backgroundQueue = dispatch_get_global_queue(qualityOfServiceClass, 0)
dispatch_async(backgroundQueue) { () -> Void in
if string != nil && string != "" {
self.highlightedString = NSMutableAttributedString(string: string!)
for i in 0..<self.syntaxDictionairy.collections.count {
for iB in 0..<self.syntaxDictionairy.collections[i].wordCollection.count {
let currentWordToCheck = self.syntaxDictionairy.collections[i].wordCollection[iB]
self.baseString = NSMutableString(string: string!)
while self.baseString.containsString(self.syntaxDictionairy.collections[i].wordCollection[iB]) {
let nsRange = (self.baseString as NSString).rangeOfString(currentWordToCheck)
let newSyntaxRange = SyntaxRange(color_I: self.syntaxDictionairy.collections[i].color, range_I: nsRange)
self.ranges.append(newSyntaxRange)
var replaceString = ""
for _ in 0..<nsRange.length {
replaceString += "§" // secret unallowed character
}
self.baseString.replaceCharactersInRange(nsRange, withString: replaceString)
}
}
}
for i in 0..<self.ranges.count {
self.highlightedString.addAttribute(NSForegroundColorAttributeName, value: self.ranges[i].color, range: self.ranges[i].range)
}
}
dispatch_sync(dispatch_get_main_queue()) { () -> Void in
completion(finished: true)
}
}
}
}
在 ViewController 中:
这是您将与 UITextfield 一起使用的代码。
首先创建一个荧光笔实例并设置你的单词字典和相应的颜色。然后在需要的时候启动运行函数。
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var myTextfield: UITextField!
var syntaxHighLighter : HighLighter! // declare highlighter
override func viewDidLoad() {
super.viewDidLoad()
setUpHighLighter()
}
// this is just a little function to put the set up for the highlighter outside of viewDidLoad()
func setUpHighLighter() {
// build a dict of words to highlight
let redColor = UIColor(red: 0.5, green: 0.0, blue: 0.0, alpha: 1.0)
let blueColor = UIColor(red: 0.0, green: 0.0, blue: 0.5, alpha: 1.0)
let greenColor = UIColor(red: 0.0, green: 0.5, blue: 0.0, alpha: 1.0)
let redGroup = SyntaxGroup(wordCollection_I: ["red","bordeaux"], type_I: "Color", color_I: redColor)
let blueGroup = SyntaxGroup(wordCollection_I: ["coralblue","blue","skyblue","azur"], type_I: "Color", color_I: blueColor)
let greenGroup = SyntaxGroup(wordCollection_I: ["green"], type_I: "Color", color_I: greenColor)
let dictionairy : SyntaxDictionairy = SyntaxDictionairy()
dictionairy.collections.append(blueGroup)
dictionairy.collections.append(greenGroup)
dictionairy.collections.append(redGroup)
syntaxHighLighter = HighLighter(syntaxDictionairy_I: dictionairy)
}
// this is where the magic happens, place the code from inside the editingChanged inside your function that responds to text changes.
@IBAction func editingChanged(sender: UITextField) {
syntaxHighLighter.run(myTextfield.text) { (finished) -> Void in
self.myTextfield.attributedText = self.syntaxHighLighter.highlightedString
}
}
}
也许你可以实现文本视图委托来检测用户何时完成输入,有条件地询问所写文本是否是你想要的,如果是,则做一些事情(改变颜色)。
这里有一些文档 https://developer.apple.com/library/ios/documentation/UIKit/Reference/UITextViewDelegate_Protocol/
你可以尝试实现这样的东西:
let text: UITextView? //this must be binded with the storyboard ui
//MARK UITextViewDelegate
func textViewDidChange(_ textView: UITextView){
if (textView.text == "bla"){
textView.colour == UIColour(Red)
}
}
此代码只是一个架构。阅读文档并检查语法。希望对你有帮助!!
联邦
我的应用程序中有一个文本视图,允许用户在其中键入任何内容。我希望文本视图在输入时检测到一些单词并改变它们的颜色。
例如,如果用户输入-"My favourite colour is red",那么我希望单词'red'得到文本颜色'red'。但是,thus 应该在句子中输入 red 之后立即发生。我应该如何实施?
你必须使用 attributedText 在 UITextView 委托方法中
- (void)textViewDidChange:(UITextView *)textView
这将解决您的问题。
我认为你应该做的是这个(如果我错了请纠正我,因为我没有 Xcode 在这台计算机上进行测试,但这应该可以工作)。如果这不起作用,请执行 Fawad Masud 并将其添加到视图中并加载...
yourTextView.addTarget(self, action: "textViewDidChange:",forControlEvents: UIControlEvents.EditingChanged)
override func viewDidLoad() {
super.viewDidLoad()
yourTextView.delegate = self //Basically makes the function below applicable to this textview
}
func textViewDidChange(textView: UITextView) { //Every time text changes this code is run
var textViewText = yourTextView.text as NSString!
if textViewText.containsString("red") {
textViewText.textColor = UIColor.redColor()
}
}
textField.addTarget(self, action: "textFieldDidChange:",forControlEvents: UIControlEvents.EditingChanged)
func textFieldDidChange(textField: UITextField) {
//your code
var main_string = textField.text
var string_to_color = "red"
var range = (main_string as NSString).rangeOfString(string_to_color)
var attributedString = NSMutableAttributedString(string:main_string)
attributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor() , range: range)
}
你需要三样东西:
在界面生成器中,您需要使用其中一种委托方法。我认为 "editingChanged" 是这里最好的。从带有 "ctrl" 的文本字段拖动到您的文档。
您需要一种方法来遍历文本字段中的字符串并检测单词。
componentsSeparatedByCharactersInSet
您需要一种为句子中的单词设置样式的方法。
NSMutableAttributedString
也很有趣:
部分代码(扔在操场上):
这会找到所有要更改的词,但会删除分隔符。需要做更多工作才能完成代码。
var strSeperator : NSCharacterSet = NSCharacterSet(charactersInString: ",.:;?! ")
var strArray = str.componentsSeparatedByCharactersInSet(strSeperator)
var styledText = NSMutableAttributedString()
for i in 0..<strArray.count {
let currentWord = strArray[i]
var currentBoolFoundInControl : Bool = false
for iB in 0..<colorTheseStrings.count {
let controlWord = colorTheseStrings[iB]
if controlWord == currentWord {
currentBoolFoundInControl = true
// add to mutable attributed string in a color
}
}
var attrString1 = NSMutableAttributedString(string: "\(strArray[i]) ")
if currentBoolFoundInControl == true {
var range = (strArray[i] as NSString).rangeOfString(strArray[i])
if strArray[i] == "red" {
attrString1.addAttribute(NSForegroundColorAttributeName, value: UIColor(red: 0.5, green: 0.0, blue: 0.0, alpha: 1.0), range: range)
} else if strArray[i] == "blue" {
attrString1.addAttribute(NSForegroundColorAttributeName, value: UIColor(red: 0.0, green: 0.0, blue: 0.5, alpha: 1.0), range: range)
}
}
styledText.appendAttributedString(attrString1)
}
myTextField.attributedText = styledText
还有一种方法:
我觉得这种方式是最稳健最酷最高效的。 代码可以稍微清理一下,可以使用更多 style/flair。这对于 "sky blue" 之类的东西确实有问题,因为它会首先找到 "blue" 并替换它。但我不得不留下一些改进的余地。 ;)
我情不自禁,所以我解决了最后一个问题。
再一次,我修复了,我的修复。现在效率更高,实际上更正了。
第一部分是 HighLighter class,将其放在单独的文档中。
// text hightlighter
class SyntaxGroup {
var wordCollection : [String] = []
var type : String = ""
var color : UIColor = UIColor(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
init(wordCollection_I : [String], type_I : String, color_I: UIColor) {
wordCollection = wordCollection_I
type = type_I
color = color_I
}
}
class SyntaxDictionairy {
var collections : [SyntaxGroup] = []
}
class SyntaxRange {
var range : NSRange
var color : UIColor
init (color_I : UIColor, range_I : NSRange) {
color = color_I
range = range_I
}
}
class HighLighter {
var ranges : [SyntaxRange] = []
var baseString : NSMutableString = NSMutableString()
var highlightedString : NSMutableAttributedString = NSMutableAttributedString()
var syntaxDictionairy : SyntaxDictionairy
init (syntaxDictionairy_I : SyntaxDictionairy) {
syntaxDictionairy = syntaxDictionairy_I
}
func run(string : String?, completion: (finished: Bool) -> Void) {
ranges = [] // reset the ranges, else it crashes when you change a previous part of the text
highlightedString = NSMutableAttributedString() // make sure all strings start fresh
baseString = NSMutableString() // make sure all strings start fresh
// multi threading to prevent locking up the interface with large libraries.
let qualityOfServiceClass = QOS_CLASS_DEFAULT
let backgroundQueue = dispatch_get_global_queue(qualityOfServiceClass, 0)
dispatch_async(backgroundQueue) { () -> Void in
if string != nil && string != "" {
self.highlightedString = NSMutableAttributedString(string: string!)
for i in 0..<self.syntaxDictionairy.collections.count {
for iB in 0..<self.syntaxDictionairy.collections[i].wordCollection.count {
let currentWordToCheck = self.syntaxDictionairy.collections[i].wordCollection[iB]
self.baseString = NSMutableString(string: string!)
while self.baseString.containsString(self.syntaxDictionairy.collections[i].wordCollection[iB]) {
let nsRange = (self.baseString as NSString).rangeOfString(currentWordToCheck)
let newSyntaxRange = SyntaxRange(color_I: self.syntaxDictionairy.collections[i].color, range_I: nsRange)
self.ranges.append(newSyntaxRange)
var replaceString = ""
for _ in 0..<nsRange.length {
replaceString += "§" // secret unallowed character
}
self.baseString.replaceCharactersInRange(nsRange, withString: replaceString)
}
}
}
for i in 0..<self.ranges.count {
self.highlightedString.addAttribute(NSForegroundColorAttributeName, value: self.ranges[i].color, range: self.ranges[i].range)
}
}
dispatch_sync(dispatch_get_main_queue()) { () -> Void in
completion(finished: true)
}
}
}
}
在 ViewController 中: 这是您将与 UITextfield 一起使用的代码。 首先创建一个荧光笔实例并设置你的单词字典和相应的颜色。然后在需要的时候启动运行函数。
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var myTextfield: UITextField!
var syntaxHighLighter : HighLighter! // declare highlighter
override func viewDidLoad() {
super.viewDidLoad()
setUpHighLighter()
}
// this is just a little function to put the set up for the highlighter outside of viewDidLoad()
func setUpHighLighter() {
// build a dict of words to highlight
let redColor = UIColor(red: 0.5, green: 0.0, blue: 0.0, alpha: 1.0)
let blueColor = UIColor(red: 0.0, green: 0.0, blue: 0.5, alpha: 1.0)
let greenColor = UIColor(red: 0.0, green: 0.5, blue: 0.0, alpha: 1.0)
let redGroup = SyntaxGroup(wordCollection_I: ["red","bordeaux"], type_I: "Color", color_I: redColor)
let blueGroup = SyntaxGroup(wordCollection_I: ["coralblue","blue","skyblue","azur"], type_I: "Color", color_I: blueColor)
let greenGroup = SyntaxGroup(wordCollection_I: ["green"], type_I: "Color", color_I: greenColor)
let dictionairy : SyntaxDictionairy = SyntaxDictionairy()
dictionairy.collections.append(blueGroup)
dictionairy.collections.append(greenGroup)
dictionairy.collections.append(redGroup)
syntaxHighLighter = HighLighter(syntaxDictionairy_I: dictionairy)
}
// this is where the magic happens, place the code from inside the editingChanged inside your function that responds to text changes.
@IBAction func editingChanged(sender: UITextField) {
syntaxHighLighter.run(myTextfield.text) { (finished) -> Void in
self.myTextfield.attributedText = self.syntaxHighLighter.highlightedString
}
}
}
也许你可以实现文本视图委托来检测用户何时完成输入,有条件地询问所写文本是否是你想要的,如果是,则做一些事情(改变颜色)。 这里有一些文档 https://developer.apple.com/library/ios/documentation/UIKit/Reference/UITextViewDelegate_Protocol/ 你可以尝试实现这样的东西:
let text: UITextView? //this must be binded with the storyboard ui
//MARK UITextViewDelegate
func textViewDidChange(_ textView: UITextView){
if (textView.text == "bla"){
textView.colour == UIColour(Red)
}
}
此代码只是一个架构。阅读文档并检查语法。希望对你有帮助!!
联邦