Search code examples
iosautolayout

View with height = 0.5 not always visible on iPad 2


I have a few text fields and separator views between them that have a height of 0.5 pixels that is set via Auto Layout.

Problem:

Sometimes some of the separators are invisible, other times they become visible but some others become invisible instead.

Is it because iPad 2 doesn't have a Retina display and things that are less than 1 pixel get rounded to 0 or 1 pixel?

If so, what is the easiest way to make them always end up 1 pixel in size on such devices? I was thinking of making a custom UIView subclass for separators that would have a height of 0.5 on Retina displays and 1 pixel otherwise.


Solution

  • Setting a view to a height of 0.5 has issues on various screens. On the iPad 2 it may result in the view not being visible at all, because it doesn't have a retina screen and thus there are no corresponding pixels for a 0.5pt line. On an iPhone Plus with its 3x screen you will most likely also get alias effects.

    To properly set a thin line on various screens (from what I can say, that's what Apple does e.g. with their table view separators), you need to calculate the width based on the screen.

    Given your receiver is a UIView that owns the line view you want to configure, this should do the trick:

    Objective-C: CGFloat lineHeight = 1.0/self.contentScaleFactor;

    Swift: let lineHeight = 1.0/contentScaleFactor

    You could do that e.g. in didMoveToWindow in the view, as the scale could theoretically change when moving windows. This is rare on iOS but potentially your view could be shown on an external screen.