3

I want to know if there is a way to determine if a UILabel is full of text. For example, if a have a label with size of:

|         |

I want to know when the label is full of text, such as:

|.........| 

I need to fill its with dots until it reaches the textFields width.

Ahmad F
  • 30,560
  • 17
  • 97
  • 143
  • You can get the label width and the width of the text (via https://stackoverflow.com/q/1324379/2442804 ) and compare the two – luk2302 May 25 '17 at 18:42

2 Answers2

3

Well, If I got it right, probably what are you looking for is Label intrinsicContentSize:

The natural size for the receiving view, considering only properties of the view itself.

the width of the label intrinsicContentSize should be the actual width of the label, doesn't matter what's the frame.size.width value.

Based on that, you simply implement:

let lbl = UILabel(frame: CGRect(x: 0, y: 0, width: 150, height: 21))

print(lbl.frame.size.width)
// 150.0

lbl.text = ""

let intrinsicSizeWidth = lbl.intrinsicContentSize.width
// since the label text is still empty, its value should be 0.0

print(intrinsicSizeWidth)

while lbl.intrinsicContentSize.width < lbl.frame.size.width {
    lbl.text?.append(".")
}

print(lbl.text!)
// ................................

Note that increasing your label width would leads to contains more dots:

let lbl = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 21))

.
.
.

print(lbl.text!)
// ...........................................

Obviously, if you would like to compare it with a UITextField -for instance- (as you mentioned in the question), it should be:

// "textField" the name of your text field...
while lbl.intrinsicContentSize.width < textField.frame.size.width {
    lbl.text?.append(".")
}
Ahmad F
  • 30,560
  • 17
  • 97
  • 143
1

Create label with frame and default text

let label = UILabel(frame: CGRect(x: 0, y: 0, width: 300, height: 100))
label.text = ""

Populate text with dots until text's width reaches label's width

while label.sizeThatFits(label.frame.size).width <= label.frame.width {
    label.text = label.text! + "."
}
Jože Ws
  • 1,754
  • 17
  • 12