1

Hi I am trying to use a UITextbox and restrict the number of characters input by the user to 10.

I have looked at using the below link,

Max length UITextField

My Questions,

1.Its not working as characters are depreciated in Swift 4 so the string.characters.count is throwing an error so what would be a workaround in Swift 4?

2.After the user enters his x number of characters, I want to make the reminders that is (limitlength - x) into empty spaces (ascii for space = 32 in decimal) so that reminder of the byte array is equal to dec 32.

I have tried doing this,

if let receivedData = rxCharacteristic?.value
    let myByteArray = Array(receivedData) {

  let b0 = myByteArray[0]
  let b1 = myByteArray[1]
  let b2 = myByteArray[2]
  let b3 = myByteArray[3]

//Now reading data from textbox input

   var userdata = textbox.text
   let userdataarray: [UInt8] = Array(userdata!.utf8)

//I tried putting values into myByteArray as below

   userdataarray[0] = myByteArray[0]
   userdataarray[1] = myByteArray[1]
   userdataarray[2] = myByteArray[2]



 //The last value in myByteArray will remain unchanged so I'm not overwriting it

So from the question when I try to input textbox data less than its length its throwing an index out of range exception. But I went a little extreme to try the below code.

 if(userdataarray[0] != 0 && userdataarray[0] != nil)
 {
  userdataarray[0] = myByteArray[0]
 }
 else
{
 userdataarray[0] = 32 //Which is space in ascii
 userdataarray[0] = myByteArray[0]
}

I don't think it worked but wanted to check on how its properly done?

nar0909
  • 135
  • 2
  • 14
  • In swift4 You can directly use string.count to get count of characters , If you want to show remaining characters you may truncate space from string and then use minus from total length so you don't need to relay on ascii – Prashant Tukadiya Dec 20 '17 at 06:08
  • @PrashantTukadiya but I need the ascii because I'm writing dec -> ascii byte arrays to ble peripheral where its displayed in ascii . For example "hello world" is an ascii for "104101108108111032119111114108100" where the 32 in the center is the space? – nar0909 Dec 20 '17 at 07:46

1 Answers1

1

If I understand your question correctly, then your trials are very much overenginering. In Swift you can just add characters to a String (as long as it is declared as var that is). This just boils down to

let orig = "Hello World"
var copy = orig
while copy.count < 15 {
    copy.append(" ")
}
let dta = copy.data(using:.isoLatin1)!
let arr = Array(dta)

Since Swift is using some Unicode-encoding internally it is probably crucial to convert your String to data using a specific encoding if you plan to "directly" transfer it to some device that is limited to a certain character set. Still a lot less code than what you provided.

Patru
  • 4,481
  • 2
  • 32
  • 42