如何在Swift 4中屏蔽文本字段?

时间:2019-03-22 09:33:50

标签: swift textfield masking

我想在textfield.text中屏蔽电子邮件,但是我只在中间得到值。我想像下面的示例一样,将值从中间传递到@ gmail.com。

例如:

  1. 让var = 12345678@gmail.com

output = **** 5678@gmail.com

  1. 让var = 123456789@gmail.com

output = **** 56789@gmail.com

    let email = "123456789@gmail.com"

    let components = email.components(separatedBy: "@")

    let result = hideMidChars(components.first!) + "@" + components.last!

    print(result)

我得到的输出:**** 5 **** @ gmail.com

我的期望:**** 56789@gmail.com

2 个答案:

答案 0 :(得分:0)

尝试扩展字符串协议并声明一个返回.init(repeating:,count)的变量:

extension StringProtocol {
    var masked: String {
        return String(repeating: "•", count: Swift.max(0, count - count/2)) + suffix(count/2)
    }
}

用法如下:

let email = "123456789@gmail.com"

print(email.masked)   //"••••••••••gmail.com"

如果要显示一部分电子邮件,只需按如下所示操作后缀(计数-3):

return String(repeating: "•", count: Swift.max(0, count - count/2)) + suffix(count/2)

答案 1 :(得分:-1)

func hide(email: String) -> String {

    let parts = email.split(separator: "@")
    if parts.count < 2 {
        return email
    }
    let name = parts[0]
    let appendix = parts[1]
    let lenght = name.count
    if lenght == 1 {
        return "*@\(appendix)"
    }
    let semiLenght = lenght / 2

    var suffixSemiLenght = semiLenght
    if (lenght % 2 == 1) {
        suffixSemiLenght += 1
    }

    let prefix = String(repeating: "*", count: semiLenght)
    let lastPart = String(name.suffix(suffixSemiLenght))

    let result = "\(prefix)\(lastPart)@\(appendix)"
    return result
}
let email = "123456789@gmail.com"
let result = hide(email: email)
print(result)