Search code examples
iosswiftxcodewidthuiscreen

Get screen width to automatically fit content with UIScreen?


I'm using the newest version of Xcode and Swift.

I have a Navigation Bar with a Navigation Item Title.

On some devices with smaller screens this title is too long so it's getting truncated.

My idea is:

  1. First I count how many characters fit on a specific width. (Of course with an allowance of 2-3 characters, because some characters are bigger than others.)

  2. I have to possible titles, the one is longer with a width of x characters, the other is the shorter alternate with a width of y characters.

  3. Now I check if the longer title will fit depending on its character count and the maximum count of characters the current screen can take. If not, I'll present its shorter alternate.

I want to do the measurement of the screen width with the following code:

let screenWidth = UIScreen.main.bounds.size.width
  1. Is this the right one to do this? Or will this e.g. output different values depending on screen resolution, although the real width of the device is the same …

  2. What unit is this? Pixels?

Note: The app is in portrait mode, so width is also the real devices width.


Solution

  • What unit is this? Pixels?

    From the docs:

    The bounding rectangle of the screen, measured in points.

    So it's points.

    Is this the right one to do this?

    Since you are trying to get the navigation bar's width, why not just get the navigation bar's width?

    navigationController?.navigationBar.bounds.width
    

    This is going to be the same value as UIScreen.main.bounds.width when the navigation bar covers the whole width of the screen, but it makes a lot more sense this way, doesn't it?

    Also, just FYI, you can check whether the screen width is small with trait collections. Although this is not as accurate as calculating the characters' size, it is the recommended way by Apple when you are trying to adapt your UI to different screen sizes.

    if traitCollection.horizontalSizeClass == .compact {
        // small screen width
    } else {
        // big screen width
    }