Ashyam
Ashyam

Reputation: 706

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!

Upvotes: 1

Views: 2973

Answers (2)

Hindu
Hindu

Reputation: 2924

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

Upvotes: 1

Jiri Trecak
Jiri Trecak

Reputation: 5122

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!

Upvotes: 0

Related Questions