Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a line width of 0.5 pixels

In iOS 7, the table view's separator line is thinner than previous iOS, and it looks like its 0.5 px width.

I need to split a cell in 2, with a similar separator line (only vertically) and I want this line to be the same width as the regular separator line.

So I'm wondering what is the best way to add such a line?

If I use a UIView and set its width to 0.5 it won't be visible, and if I set its width to 1.0, then of course I will get a line width of 1.0px not 0.5px.

I tried to use a resource with a retina size of 1.0px but it didn't work either

like image 385
Eyal Avatar asked Feb 04 '14 12:02

Eyal


3 Answers

You set the width as 0.5 - or to make it always 1 pixel then set it to (1.0 / [UIScreen mainScreen].scale)

I've done this before and it's worked fine

I think the reason you can't see it is that you are centering the line exactly in the middle of the screen, which will make the line's origin (320 - 0.5) / 2.0, being an X origin of 159.75 - the 0.75 may be messing things up - or the cell is removing the background color of your view

like image 191
SomeGuy Avatar answered Oct 09 '22 09:10

SomeGuy


I did this steps:

  1. Create a constraint with 1px height
  2. Connect the constraint with IBOutlet (file .m)
  3. Change the constant of the constraint for 0.5 in the ViewDidLoad

It works for me.

like image 33
anthonyqz Avatar answered Oct 09 '22 09:10

anthonyqz


Assuming you do your cell layouts with Storyboards:

Place an UIView with your desired height and 1px width into your cell. Give it whatever background color you'll like it to have. The standard separator color is approx. RGB(200,199,204).

Then create a subclass of UIView, e.g. HairlineView and override awakeFromNib()

-(void)awakeFromNib {
    self.layer.borderColor = [self.backgroundColor CGColor];
    self.layer.borderWidth = (1.0 / [UIScreen mainScreen].scale) / 2;

    self.backgroundColor = [UIColor clearColor];
}

You're drawing a border around your 1px wide view, which is 2 * 0.25px wide making it 0.5px in total, which is the width you wanted to achieve, then hide the background of the view by setting the background to clear. This last step is important, it won't work without.

Set the type of your view to HairlineView, then it should work.

When doing it programmatically, you'd have to override a different method, e.g. initWithFrame() maybe, since awakeFromNib() only gets called when you create the view from a Storyboard layout.

like image 15
Irina Anastasiu Avatar answered Oct 09 '22 11:10

Irina Anastasiu