Printing string arrays to UILabels - ios

Is there any way to print out an Array of Strings to an UILabel without any special characters, i.e. ["number1","number2","number3"]
I want it to look like this in my UILabel Output:
number1
number2
number3
Here is my code:
let addInputs = quantityField.text! + "x " + descriptionField.text!
var listArray: [String] = []
listArray.append("\(addInputs)")
for addInputs in listArray {
//itemListLabel.text = "\n\(addInputs)"
print("\(addInputs)")
itemListLabel.text = "\(listArray)"
}

You can join the items together with \n to add a hard return:
itemListLabel.text = listArray.joinWithSeparator("\n")

You will need to do 2 things:
itemListLabel.numberOfLines = listArray.count
itemListLabel.text = listArray.joinWithSeparator("\n")
The first line sets the number of lines to display in the label. If you know beforehand what you want, you can just set this in Interface Builder. The second line joins the array of strings with a new-line separator between each.

Swift 5.3
itemListLabel.text = listArray.joined(separator: "\n")

Related

Remove parentheses from array value converted to string

I have a textview and when displaying text there are parentheses in the text. I want to eliminate them. This is my code:
self.txtpstn.text = "\(self.no_pstn.self as NSArray)"
self.txtmobile.text = "\(self.no_mobile.self as NSArray)"
This is the display on the application:
Use join:
self.txtpstn.text = "\((self.no_pstn.self as NSArray).componentsJoined(by: ","))"
self.txtmobile.text = "\(self.no_mobile.self as NSArray).componentsJoined(by: ","))"

How to handle the %s format specifier

Objective-C code:
NSString *str = #"hi";
NSString *strDigit = #"1934"; (or #"193" may be a 3 digit or 4 digit value)
[dayText appendFormat:#"%#%4s,str,[strDigit UTF8String]];
The Objective-C code handles the output string with current alignment when it appears with 3 or 4 digits as output. It is correctly aligning to left and doesn't matter how much digits it is. Any one know how to handle this in Swift?
In Swift I tried with below code and the string is not adjusting the alignment according to the number of digits.
textForTrip += "\(str) \(String(format:"%4s", (strDigit.utf8))"
The %s format expects a pointer to a (NULL-terminated) C string
as argument, that can be obtained with the withCString method.
This would produce the same output as your Objective-C code:
let str = "Hi"
let strDigit = "193"
let text = strDigit.withCString {
String(format: "%#%4s", str, $0)
}
print(text)
It becomes easier if you store the number as integer instead of a
string:
let str = "Hi"
let number = 934
let text = String(format: "%#%4d", str, number)
print(text)
Try this below approach, that might help you
let strDigit = "\("1934".utf8)" //(or #"193" may be a 3 digit or 4 digit value)
var dayText = "Hello, good morning."
dayText += "\(strDigit.prefix(3))"

How to get frequency of line feed in string by swift

Sorry,I'm new of swift. I want to calculate the target char in string.But I don't know how to do.Have any good suggestion to me?Thanks.
let string = "hello\nNice to meet you.\nMy name is Leo.\n" //I want to get 3
If you simply want a count of newline characters then you can use a filter on the string's characters:
let string = "hello\nNice to meet you.\nMy name is Leo.\n"
let count = string.characters.filter { $0 == "\n" }.count
print(count)
This outputs 3 as expected.
An alternative is to split the lines with the components(separatedBy method:
let string = "hello\nNice to meet you.\nMy name is Leo.\n"
let lineCounter = string.components(separatedBy: "\n").count - 1
or more versatile to consider all kinds of newline characters
let lineCounter = string.components(separatedBy: CharacterSet.newlines).count - 1
Due to the trailing newline character the result is 4. To ignore a trailing new line you have to decrement the result.

Add string to beginning of another string

Basic question
I have 2 strings. I want to add one string to another? Here's an example:
var secondString= "is your name."
var firstString = "Mike, "
Here I have 2 strings. I want to add firstString to secondString, NOT vice versa. (Which would be: firstString += secondString.)
More detail
I have 5 string
let first = "7898"
let second = "00"
let third = "5481"
let fourth = "4782"
var fullString = "\(third):\(fourth)"
I know for sure that third and fourth will be in fullString, but I don't know about first and second.
So I will make an if statement checking if second has 00. If it does, first and second won't go in fullString. If it doesn't, second will go intofullString`.
Then I will check if first has 00. If it does, then first won't go inside of fullString, and if not, it will go.
The thing is, I need them in the same order: first, second, third fourth. So in the if statement, I need a way to potentially add first and second at the beginning of fullString.
Re. your basic question:
secondString = "\(firstString)\(secondString)"
or
secondString = firstString + secondString
Here is a way to insert string at the beginning "without resetting" per your comment (first at front of second):
let range = second.startIndex..<second.startIndex
second.replaceRange(range, with: first)
Re. your "more detail" question:
var fullString: String
if second == "00" {
fullString = third + fourth
} else if first == "00" {
fullString = second + third + fourth
} else {
fullString = first + second + third + fourth
}
From the Apple documentation:
String values can be added together (or concatenated) with the addition operator (+) to create a new String value:
let string1 = "hello"
let string2 = " there"
var welcome = string1 + string2
// welcome now equals "hello there"
You can also append a String value to an existing String variable with the addition assignment operator (+=):
var instruction = "look over"
instruction += string2
// instruction now equals "look over there"
You can append a Character value to a String variable with the String type’s append() method:
let exclamationMark: Character = "!"
welcome.append(exclamationMark)
// welcome now equals "hello there!"
So you are pretty much free to add these in any way shape or form.
Which includes
secondstring += firststring
Edit to accommodate the new information:
Strings in Swift are mutable which means you can always add to a string in-place without recreating any objects.
Something like (pseudo-code)
if(second != "00")
{
fullstring = second + fullstring
//only do something with first if second != 00
if(first != "00")
{
fullstring = first + fullstring
}
}

Line break in UILabel (Xcode 7 Swift)

So I have an array of elements of type float. And I have a UILabel which is supposed to display each of these elements of the array on DIFFERENT LINES.
The Array is
var history = [Float]()
I used a for loop to go through each element and append it to the UILabel
for(i=0; i<size; i++){
currentString = String(history[i])
result.text = result.text! + "\n" + currentString
}
result is the UILabel.
I tried using \n but it doesn't seem to recognise it. Any solutions for this in Swift. Thanks in advance!
You can try below to solve your issue.
let history = [1.0, 2.0, 3.0, 4.0]
var result = ""
self.lbl.text = ""
for var i=0; i < history.count; i++
{
let currentString = NSString(format: "%.2f", history[i])
self.lbl.text = self.lbl.text! + "\n" + (currentString as String)
}
And Line Number should be 0. I set that from XIB.
Thanks
The first thing I would check is if your label has (it is stupid mistake, but can happen to all of us)
label.numberOfLines = 0
Assuming that is true, instead of building the string by hand, you could use in-built function join(). Sadly, since it is not String array, you can't use it directly, but you have to create string array first
// Get both storages
var history = [Float]() // Filled with your data
var stringHistory = [String]()
// Convert each number to string
for value in history {
stringHistory.append(String(value))
}
// Finally, join array to one string using \n as separator
let finalString = "\n".join(stringHistory)
Hope some of this helps!

Resources