Show generated passwords with colors

This commit is contained in:
yishilin14 2017-02-26 00:58:18 +08:00
parent 62db5da62f
commit 30ae32ec5f
3 changed files with 18 additions and 15 deletions

View file

@ -125,6 +125,19 @@ class Utils {
} }
} }
} }
static func attributedPassword(plainPassword: String) -> NSAttributedString{
let attributedPassword = NSMutableAttributedString.init(string: plainPassword)
// draw all digits in the password into red
// draw all punctuation characters in the password into blue
for (index, element) in plainPassword.unicodeScalars.enumerated() {
if NSCharacterSet.decimalDigits.contains(element) {
attributedPassword.addAttribute(NSForegroundColorAttributeName, value: Globals.red, range: NSRange(location: index, length: 1))
} else if NSCharacterSet.punctuationCharacters.contains(element) {
attributedPassword.addAttribute(NSForegroundColorAttributeName, value: Globals.blue, range: NSRange(location: index, length: 1))
}
}
return attributedPassword
}
} }
// https://gist.github.com/NikolaiRuhe/eeb135d20c84a7097516 // https://gist.github.com/NikolaiRuhe/eeb135d20c84a7097516

View file

@ -23,14 +23,15 @@ class FillPasswordTableViewCell: ContentTableViewCell {
} }
@IBAction func generatePassword(_ sender: UIButton) { @IBAction func generatePassword(_ sender: UIButton) {
contentTextField.text = Utils.randomString(length: 16) let plainPassword = Utils.randomString(length: 16)
contentTextField.attributedText = Utils.attributedPassword(plainPassword: plainPassword)
} }
override func getContent() -> String? { override func getContent() -> String? {
return contentTextField.text return contentTextField.attributedText?.string
} }
override func setContent(content: String) { override func setContent(content: String) {
contentTextField.text = content contentTextField.attributedText = Utils.attributedPassword(plainPassword: content)
} }
} }

View file

@ -71,18 +71,7 @@ class LabelTableViewCell: UITableViewCell {
func revealPassword(_ sender: Any?) { func revealPassword(_ sender: Any?) {
if let plainPassword = cellData?.content { if let plainPassword = cellData?.content {
let attributePassword = NSMutableAttributedString.init(string: plainPassword) contentLabel.attributedText = Utils.attributedPassword(plainPassword: plainPassword)
// draw all digits in the password into red
// draw all punctuation characters in the password into blue
for (index, element) in plainPassword.unicodeScalars.enumerated() {
if NSCharacterSet.decimalDigits.contains(element) {
attributePassword.addAttribute(NSForegroundColorAttributeName, value: Globals.red, range: NSRange(location: index, length: 1))
} else if NSCharacterSet.punctuationCharacters.contains(element) {
attributePassword.addAttribute(NSForegroundColorAttributeName, value: Globals.blue, range: NSRange(location: index, length: 1))
}
}
// set contentLabel
contentLabel.attributedText = attributePassword
} else { } else {
contentLabel.text = "" contentLabel.text = ""
} }