Kri*_*ana 3 uitextview ios swift xcode6
我的应用程序中有一个文本视图,允许用户在其中键入任何内容.我希望文本视图在键入时检测几个单词并更改其颜色.
例如,如果用户输入"我最喜欢的颜色是红色",那么我希望单词"红色"使文本颜色为"红色".但是因此应该在句子中输入红字后立即发生.我该如何实现呢?
你需要三件事:
在界面构建器中,您需要使用其中一个委托方法.我认为"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
Run Code Online (Sandbox Code Playgroud)
还有一种方法:
我认为这种方式最强大,最酷,最有效.代码可以清理一下,可以使用更多的风格/风格.这确实有"天蓝色"之类的问题,因为它会首先找到"蓝色"并替换它.但我不得不留下一些改进空间.;)
我无法自拔,所以我解决了最后一个问题.
我再次修复了我的问题.现在更高效,实际上更正.
第一部分是HighLighter类,将其放在单独的文档中.
// 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)
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
在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
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
772 次 |
| 最近记录: |