Monday, November 7, 2016

Getting Height or Width of Text

You use UIView.sizeThatFits to get the best size to fit a given size.

  • To get width, fix the height and maximize the width of your given size.
  • To get height, fix the width and maximize the height of your given size.

Code Example of Getting Width of Text

 
@IBOutlet weak var sampleTextLabel: UILabel!

@IBOutlet weak var widthTextField: UITextField!

override func viewDidLoad() {
    super.viewDidLoad()
    
    // Fix the height to get the width.
    let suggestedSize = CGSize(width: CGFloat.greatestFiniteMagnitude, 
                               height: sampleTextLabel.frame.height)
    widthTextField.text = sampleTextLabel.sizeThatFits(suggestedSize).width.description
}
 
Note: CGFloat.greatestFiniteMagnitude gives you the maximum number for a float.

(Xcode 8, Swift 3.0)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.

SwiftUI Search & Filter with Combine - Part 3 (iOS, Xcode 13, SwiftUI, 2...

In part 3 of the Searchable video series, I show you how to use Combine in #SwiftUI for the search and filter logic connected to the searcha...