ios - add prefix to UITextField -


i want add prefix of uitextfield text. uitextfield text length less 7. how many characters less 7, replace zeros.

if text "1234", add prefix "0001234". if text "12345", add prefix "0012345". if text "123", add prefix "0000123".

can 1 suggest me, how implement.

it sounds want numbers-only string 7-characters long, left-most characters filled in padded zeros user has not entered, correct?

so, need handful of methods make easy possible.

first, 1 doesn't make sense right now, want method remove zeros padded @ front (it'll make sense later).

so, borrowing stack overflow answer...

- (nsstring *)stringbyremovingpaddedzeros:(nsstring *)string {     nsrange range = [string rangeofstring:@"^0*" options:nsregularexpressionsearch];     return [string stringbyreplacingcharactersinrange:range withstring:@""]; } 

and we'll borrow ilesh's answer adding padded zeros:

- (nsstring *)stringbyaddingpaddedzeros:(nsstring *)string padlength:(nsinteger)length {     nsstring *padding = [@"" stringbypaddingtolength:(length - string.length) withstring:@"0" startingatindex:0];     return [nsstring stringwithformat:@"%@%@", padding, string]; } 

so can go , forth between padded , unpadded strings, right?

so now, 1 last step, implementing shouldchangecharactersinrange:

- (bool)textfield:(uitextfield *)textfield shouldchangecharactersinrange:(nsrange)range replacementstring:(nsstring *)string {     nsstring *newstring = [textfield.text stringbyreplacingcharactersinrange:range withstring:string];     newstring = [self stringbyremovingpaddedzeros:newstring];     newstring = [self stringbyaddedpaddedzeros:newstring padlength:7];     textfield.text = [newstring substringtoindex:7];      return no; } 

we return no here, we're setting textfield.text property manually. when there 7 characters (and no leading zeros), user can type no more. if there 7 characters , user hits backspace, should shift right 1 , 0 added front. if there are leading zeros @ front, typing characters should shift left , drop leading zero, , add new character front.

as additional note, code not take care of verifying user entering digits. logic required that. i'd recommend checking replacementstring (string) digits before of other code in shouldchangecharactersinrange here.


Comments

Popular posts from this blog

toolbar - How to add link to user registration inside toobar in admin joomla 3 custom component -

linux - disk space limitation when creating war file -