Line break in UILabel (Xcode 7 Swift) - ios

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!

Related

How to append an array to an array at current index?

I have an array myarray and I am using a for loop to get a few information which I add to myarray. But next time the for-loop runs, I don't want to create a separate index, but instead the 2nd time and so on, I want to append the information to myarray[0].
How do I do that?
var myarray = [String]()
for var j in 0 < 12 {
// do some stuff
for var i in 0 ..< 10 {
let parta = json?["users"][j]["name"].string
let partb = json?["users"][j]["Lname"].string
let partc = json?["users"][j]["dob"].string
myarray.append("\(parta)-\(partb)-\(partc)---")
// Here when the for loop comes back again (i = 1) , i dont want to make
// myarray[1] , but instead i want myarray[0] ,
// having value like [parta-partb-partc--parta-partb-partc]
}
}
Basically what I am trying to do is, append the new name/lname/dob values at myarray[0] without affecting the current value/string at myarray[0].
You can insert single element and also add array as below.
Swift 5
var myarray = [String]()
myarray.insert("NewElement", at: 0)
myarray.insert(contentsOf: ["First", "Second", "Third"], at: 0)
If I understand your question correctly, you want to create one long string and add the new data always at the beginning of the string. One way to do that would be:
// Store somewhere
var myString = String()
for var i in(0..<10) {
let parta = json?["name"].string
let partb = json?["Lname"].string
let partc = json?["dob"].string
let newString = "\(parta)-\(partb)-\(partc)---")
newString.append(myString)
myString = newString
// Here when the for loop comes back again (i = 1) , i dont want to make
//myarray[1] , but instead i want myarray[0] ,
//having value like [parta-partb-partc--parta-partb-partc]
}

Using a switch statement to construct a Regular Expression in Swift 3

I've created a function that generates a RegularExpression in Swift 3.0. I'm close to what I want, but the backslash is causing me a lot of trouble.
I've looked at Swift Documentation and I thought changing the "\" to \u{005C} or u{005C} would resolve the issue, but it doesn't.
Here's the array I'm feeding my regex generation function:
var letterArray = ["a","","a","","","","","","",""]
Here's the relevant portion of my method:
var outputString = String()
// getMinimumWordLength returns 3
let minimumWordLength = getMinimumWordLength(letterArray: letterArray)
// for the array above, maximumWordLength returns 10
let maximumWordLength = letterArray.count
var index = 0
for letter in letterArray {
if index < minimumWordLength {
if letter as! String != "" {
outputString = outputString + letter.lowercased
} else {
// this puts an extra \ in my regex
outputString = outputString + "\\w" // first \ is an escape character, 2nd one gets read
// this puts an extra backslash in, too
// outputString = outputString + "\u{005C}w"
}
}
index += 1
}
outputString = outputString + ("{\(minimumWordLength),\(maximumWordLength)}$/")
return outputString
My desired output is:
a\wa{3,10}$/
My actual output is:
a\\wa{3,10}$/
If anyone has suggestions what I'm fouling up, I welcome them. Thank you for reading.
When string is printed in debugger, escape character will be displayed. When it is displayed for user, it will not.

Printing string arrays to UILabels

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")

Xcode Swift - How to initialize a 2D array of [[AnyObject]] of as many elements you want

I know I can initialize an array of Ints for example like:
var intArray = [Int](count: 10, repeatedValue: 0)
What I want to do is something like this:
var array = Array(count:6, repeatedValue:Array(count:0, repeatedValue:AnyObject()))
(Xcode returns with: AnyObject cannot be constructed because it has no accessible initializers)
With the same outcome as I could initialize the array like:
var anyObjectArray : [[AnyObject]] = [[],[],[],[],[],[]]
But doing the above is ugly if i need like 100 rows of lets say 3
The problem is I can append in my function like:
// init array
var anyObjectArray : [[AnyObject]] = [[],[],[]]
//inside a for loop
anyObjectArray[i].append(someValue)
That works ok, until of course i gets higher then the number of rows in the array.
A answer to this problem is also acceptable if I could do something like:
anyObjectArray[append a empty row here][]
But that is probably stupid :)
I hope there is a way to do this cause I don't feel like having a line like:
var anyObjectArray : [[AnyObject]] = [ [],[],[],[],[],[],[],[],[],[],[],[],[],[],[], ... etc ]
at the top of my page ;)
Thank you for your time!
You don't need the second repeatedValue initialiser, since you want an empty array. You can just use
var array = Array(count:6, repeatedValue:[AnyObject]())
You can try with 2 loops, working as a grid :
var items: = Array<Array<Item>>()
for col in 0..<maxCol {
var colItems = Array<Item>()
for row in 0..<maxRow {
colItems.append(Item())
}
items.append(colItems)
}
//Append as much as you want after
Try this
let columns = 27
let rows = 52
var array = Array<Array<Double>>()
for column in 0... columns {
array.append(Array(count:rows, repeatedValue:Int()))
}
Try using this
let array = Array(count:6, repeatedValue:[])
for (var i=0; i<array.count; i++){
array[i] = Array(count:0, repeatedValue: AnyObject.self)
}
in place of your code.
Swift 3:
var array = Array(repeating:[AnyObject](),count:6)

IOS insert line break to data retrieved from parse.com

i am trying to retrieve some string data from parse.com and i've added "\n, \n & \r" into the data, but it still does not give me the line breaks, how do format the line below to get line breaks.
self.label.text = [NSString stringWithFormat:#"%#", [object objectForKey:#"ParseStringDate"]];
if you get the text that should be presented in multiple lines then you should try to set for your label this property:
self.label.numberOfLines = 0;
it basically means that label can be multiline, make sure that frame of that label is sufficient to show more that one line of text
if some has the same challenge in swift - please find attached a short string extension:
extension String {
func formatStringFromParseWithLineBreaks() -> String {
let sourceString: String = self
let resultString = sourceString.stringByReplacingOccurrencesOfString("\\n", withString: "\n")
return resultString
}
}
It is easy to use:
let stringFromParse = "Great\\nExample"
let newString = stringFromParse.formatStringFromParseWithLineBreaks()
Have fun
self.label.text = [NSString stringWithFormat:#"first\n%#\n another", [object objectForKey:#"ParseStringDate"]];
Make sure you have numberOfLines of the label set to 0. This should work.

Resources