After a bit of research, I assume that the solution below can automatically add / remove a new line at equal intervals.
Explanation: 1. Insert a new character.
Text : XXXX-XXXX- Location : 0123456789 Objective : We've to insert new character at locations 4,9,14,19,etc. Since equal spacing should be 4. Let assume y = The location where the new charcter should be inserted, z = Any positive value ie,[4 in our scenario] and x = 1,2,3,...,n Then, => zx + x - 1 = y eg, [ 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)*** eg, [ 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. ie, The character prefixed with customized space indicator Note: 'y' can't be zero => zx + x = y eg, [ 4 * 1 + 1 = 5 ; 4 * 2 + 2 = 10; 4 * 3 + 3 = 15; etc.] => x(z + 1) = y => ***x = y % (z + 1)*** eg, [ x = (5 % (4 + 1)) = 0; x = (10 % (4 + 1)) = 0; etc. ]
Solution in 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 }
Tesan3089 Jul 25 '16 at 6:09 2016-07-25 06:09
source share