0

I have a UILabel which is part of a [UILabel] array, I am trying to set the text of the UILabel in the following way:

yLabel[0].text = "\(yMaxValue)"

But the result is always 0.0. When I run

println(yLabel[0].text)

The result is Optional("0.0"). Is this because the UILabel is part of an array? How can I set the text of a UILabel that is part of an array?

EDIT: Screenshot of the issue, the output from println(test.text) is Optional("0.0") Screenshot

yLabels are created in this line:

private var yLabels: [UILabel] = [UILabel](count: 5, repeatedValue: UILabel())
A_toaster
  • 1,196
  • 3
  • 22
  • 50

3 Answers3

4

The problem is the way you create your array; you're not adding 5 different labels, you're adding 5 of the same label, so the label ends up with whatever value you set last (yMinValue). Create your array like so, and it should work (you should also have the "!" after text like others have pointed out),

private var yLabel = [UILabel(), UILabel(), UILabel(), UILabel(), UILabel()]
rdelmar
  • 103,982
  • 12
  • 207
  • 218
0

The reason is that it is an optional value. If you are sure that it will always have content, try:

println(ylabel[0].text!)

Look at the Apple docs for more information.

Will Richardson
  • 7,780
  • 7
  • 42
  • 56
David Hoelzer
  • 15,862
  • 4
  • 48
  • 67
0

This code should work, the most likely thing is that yMaxValue is always 0.0 for some unrelated reason.

When you get the text from the label it is wrapped in an optional because the value can be nil. To unwrap it when you print it use: println(ylabel[0].text!).

Will Richardson
  • 7,780
  • 7
  • 42
  • 56
  • Thanks for the response, unfortunately yMaxValue is not actually set to 0, but it is a CGFloat. Does it being a CGFloat change how I set the UILabel text? – A_toaster Feb 05 '15 at 01:04
  • So if you print `"\(yMaxValue)"` it doesn't show `0.0`? CGFloat to string: http://stackoverflow.com/questions/25154087/converting-cgfloat-to-string-in-swift – Will Richardson Feb 05 '15 at 01:06
  • When I print yMaxValue it is 92.0 – A_toaster Feb 05 '15 at 01:09
  • I would test by setting `yLabel[0].text = "Some static string"`. Failing that, get the `yLabel[0]` object, change it's text and then set `yLabel[0] = thatObject` to see if that works. – Will Richardson Feb 05 '15 at 01:12
  • Ok I tried what you said and posted a screenshot just in case I am making some silly error – A_toaster Feb 05 '15 at 01:18