经过一番研究,我猜下面的解决方案可以自动以相等的间隔添加/删除一个新字符串。
说明:
1.插入一个新字符
Text : XXXX-XXXX-
Location : 0123456789
Objective : We've to insert new character's at locations 4,9,14,19,etc. Since equal spacing should be 4.
Let's assume y = The location where the new charcter should be inserted,
z = Any positive value i.e.,[4 in our scenario] and
x = 1,2,3,...,n
Then,
=> zx + x - 1 = y e.g., [ 4 * 1 + (1-1) = 4 ; 4 * 2 + (2 - 1) = 9 ; etc. ]
=> x(z + 1) - 1 = y
=> x(z + 1) = (1 + y)
=> ***x = (1 + y) % (z + 1)*** e.g., [ x = (1 + 4) % (4 + 1) => 0; x = (1 + 9) % (4 + 1) => 0 ]
The reason behind finding 'x' leads to dynamic calculation, because we can find y, If we've 'z' but the ultimate objective is to find the sequence 'x'. Of course with this equation we may manipulate it in different ways to achieve many solutions but it is one of them.
2. Removing two characters (-X) at single instance while 'delete' keystroke
Text : XXXX-XXXX-
Location : 0123456789
Objective : We've to remove double string when deleting keystroke pressed at location 5,10,15,etc. i.e., The character prefixed with customized space indicator
Note: 'y' can't be zero
=> zx + x = y e.g., [ 4 * 1 + 1 = 5 ; 4 * 2 + 2 = 10; 4 * 3 + 3 = 15; etc.]
=> x(z + 1) = y
=> ***x = y % (z + 1)*** e.g., [ x = (5 % (4 + 1)) = 0; x = (10 % (4 + 1)) = 0; etc. ]
Swift 中的解决方案:
let z = 4, intervalString = " "
func canInsert(atLocation y:Int) -> Bool { return ((1 + y)%(z + 1) == 0) ? true : false }
func canRemove(atLocation y:Int) -> Bool { return (y != 0) ? (y%(z + 1) == 0) : false }
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
let nsText = textField.text! as NSString
if range.length == 0 && canInsert(atLocation: range.location) {
textField.text! = textField.text! + intervalString + string
return false
}
if range.length == 1 && canRemove(atLocation: range.location) {
textField.text! = nsText.stringByReplacingCharactersInRange(NSMakeRange(range.location-1, 2), withString: "")
return false
}
return true
}