iOS Question Using Sub TextField_TextChanged

RichardN

Well-Known Member
Licensed User
Longtime User
I have a TextField view designed to receive four digits that represent a year number. Whilst you can specify the keyboard type in designer or code, when deploying to a tablet you don't get a choice because the full keyboard is deployed regardless. In that case the user is able to enter unwanted alpha characters as well as digits.

In the absence of a 'Masked Edit' view I have to process the input keys in 'TextChanged' to weed out all but numerals. However, right from the outset the Sub does not perform quite as I expected.

B4X:
Sub txtYear_TextChanged (OldText As String, NewText As String)

End Sub

If I equate txtYear.Text to a literal within this subroutine like txtYear.Text="Some text", the view changes immediately as expected. However if I change the value of TextField.Text OR the NewText variable conditional on the value of NewText the changes do not occur.

B4X:
Sub txtYear_TextChanged (OldText As String, NewText As String)
 
    txtYear.Text = "Some String Value"      'this line works immediately and exactly  as expected
    
    'I would expect the next line to suppress the insertion of a 5th char but it
    'does not until a 6th is added when it truncates correctly to 4 chars
    If NewText.Length > 4 Then txtYear.Text = NewText.SubString2(0,4)  

End Sub

Surely this is a bug?
Is this Sub intended to work in some different way?
Should I be looking at a different solution to mask a 1-4 digit number?
 
Last edited:

Erel

B4X founder
Staff member
Licensed User
Longtime User
This code will work:
B4X:
Sub TextField1_TextChanged (OldText As String, NewText As String)
   Log(NewText)
   If NewText.Length > 4 Then CallSubDelayed2(Me, "SetText",  NewText.SubString2(0, 4))
End Sub

Sub SetText(t As String)
   TextField1.Text = t
End Sub

Another option is to make this check in the EndEdit event. The result will be more user friendly (as modifying the text while the user enters it can be annoying).
 
Upvote 0

RichardN

Well-Known Member
Licensed User
Longtime User
Thanks for the work-around Erel.

I personally don't think using the EndEdit event is at all suitable. Once you have hit an 'enter' button other code begins executing at the same time as incorrect entries are caught in the EndEdit event and an error message is displayed. You would have to start setting up flags to bug out of the 'enter' event if EndEdit found a problem... a rather messy way to do things. A proper 'masked edit' control would give a much better user experience.

Reading back I see this bug was found 7 months ago by@Shay ....Here https://www.b4x.com/android/forum/threads/substring2-not-working-well-on-ios-8.51212/#post-320682

Perhaps there is a fix for this problem on the horizon ?
 
Upvote 0
Top