Creating a horizontal line
41,444
Solution 1
Create a UIView with a black background that is 1 pixel high and 320 pixels wide.
Solution 2
Use a UIView:
UIView * separator = [[UIView alloc] initWithFrame:CGRectMake(x, y, 320, 1)];
separator.backgroundColor = [UIColor colorWithWhite:0.7 alpha:1];
[self.view addSubview:separator];
[separator release];
Solution 3
While Jasarien's solution is nice and simple, it doesn't create an actual 1 pixel hairline, but a 2 pixel wide line on 2X devices.
I found a blog post on how to create the real 1 pixel thin hairline. We need a utility UIView subclass. For Swift that would be:
import UIKit
class HairlineView: UIView {
override func awakeFromNib() {
guard let backgroundColor = self.backgroundColor?.CGColor else { return }
self.layer.borderColor = backgroundColor
self.layer.borderWidth = (1.0 / UIScreen.mainScreen().scale) / 2;
self.backgroundColor = UIColor.clearColor()
}
}
Solution 4
For Horizontal Line
UIView *horizontalLine = [[UIView alloc]initWithFrame:CGRectMake(x cordinate,y cordinate,1,linelenth)];
horizontalLine.backgroundColor = [UIColor blackColor];
[self. view addSubView:horizontalLine];
[horizontalLine release];
For Vertical Line
UIView *verticalLine = [[UIView alloc]initWithFrame:CGRectMake(x cordinate,y cordinate,linelenth,1)];
verticalLine.backgroundColor = [UIColor blackColor];
[self. view addSubView:verticalLine];
[verticalLine release];
Solution 5
Try this
extension CALayer {
func addBorder(edge: UIRectEdge, color: UIColor, thickness: CGFloat) {
let border = CALayer()
switch edge {
case .top:
border.frame = CGRect(x: 0, y: 0, width: frame.width, height: thickness)
case .bottom:
border.frame = CGRect(x: 0, y: frame.height - thickness, width: frame.width, height: thickness)
case .left:
border.frame = CGRect(x: 0, y: 0, width: thickness, height: frame.height)
case .right:
border.frame = CGRect(x: frame.width - thickness, y: 0, width: thickness, height: frame.height)
default:
break
}
border.backgroundColor = color.cgColor;
addSublayer(border)
}
Related videos on Youtube
Author by
4thSpace
Updated on June 18, 2020Comments
-
4thSpace almost 4 years
I have two labels that are stacked. If I want a horizontal line between them, is there any other way besides using an image with a UIImageView?
-
Tom Howard about 8 yearsCrud, took me a minute.
-
KevM almost 8 yearsThis answer feels dismissive. Maybe explain how you would do this in Interface Builder?
-
Red almost 5 yearsActually I think this should be the right answer! Very nice solution Thx a lot!
-
craft over 4 yearsCreates 2 pixel wide line, see @Phantrast's answer for a thinner line
-
Dani about 4 years@KevM what part needs explanation? Just give it constraints.
-
Jasarien about 4 yearsThis is a 10 year old question and answer. Let it go 🤣