隐藏一些带有星号的电话号码UIlabel用于otp验证swift 4应用

时间:2018-09-25 11:54:33

标签: swift

我正在快速开发一个应用程序,我希望发送otp时,被包围的数字标签文本显示类似的内容

“ otp发送到+91 ****** 21”

这是我现在发现的东西,我不知道应该在此处应用哪种逻辑来发布这样的字符串

var mobileNumer = "+91987654321"
let intLetters = mobileNumer.prefix(3)
let endLetters = mobileNumer.suffix(2)

我希望在输入手机号码后在标签上显示此号码,它应该显示第一个数字,然后开始显示,而母鸡显示最后两个数字

2 个答案:

答案 0 :(得分:0)

尝试一下:

var mobileNumer = "+91987654321"
let intLetters = mobileNumer.prefix(3)
let endLetters = mobileNumer.suffix(2)

let newString = intLetters + "*******" + endLetters   //"+91*******21"

或者如果您想安全:

var mobileNumer = "+91987654321"

guard mobileNumer.count > 5 else {
    fatalError("The phone number is not complete")
}

let intLetters = mobileNumer.prefix(3)
let endLetters = mobileNumer.suffix(2)

let stars = String(repeating: "*", count: mobileNumer.count - 5)

let result = intLetters + stars + endLetters

或者,如果您希望替换子范围:

var mobileNumer = "+91987654321"

guard mobileNumer.count > 5 else {
    fatalError("The phone number is not complete")
}

let startingIndex = mobileNumer.index(mobileNumer.startIndex, offsetBy: 3)
let endingIndex = mobileNumer.index(mobileNumer.endIndex, offsetBy: -2)
let stars = String(repeating: "*", count: mobileNumer.count - 5)
let result = mobileNumer.replacingCharacters(in: startingIndex..<endingIndex,
        with: stars)

如果您要突变mobileNumer

mobileNumer.replaceSubrange(startingIndex..<endingIndex, with: stars)
print(mobileNumer) //"+91*******21"

答案 1 :(得分:0)

您可以使用此功能。

queue:listen

称呼

func starifyNumber(number: String) -> String {
        let intLetters = number.prefix(3)
        let endLetters = number.suffix(2)
        let numberOfStars = number.count - (intLetters.count + endLetters.count)
        var starString = ""
        for _ in 1...numberOfStars {
            starString += "*"
        }
        let finalNumberToShow: String = intLetters + starString + endLetters
        return finalNumberToShow
    }