创build一个水平线

我有两个标签堆叠。 如果我想要它们之间的水平线,除了与UIImageView使用图像有什么其他的方式吗?

创build一个黑色背景,1像素高,320像素宽的UIView。

使用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]; 

虽然Jasarien的解决scheme非常简单,但它不会创build实际的1像素细线 ,而是2X设备上的2像素宽线。

我发现了一篇关于如何创build真实的1像素细线的博文 。 我们需要一个实用的UIView子类。 对于Swift来说,这将是:

 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() } } 

对于水平线

 UIView *horizontalLine = [[UIView alloc]initWithFrame:CGRectMake(x cordinate,y cordinate,1,linelenth)]; horizontalLine.backgroundColor = [UIColor blackColor]; [self. view addSubView:horizontalLine]; [horizontalLine release]; 

垂直线

 UIView *verticalLine = [[UIView alloc]initWithFrame:CGRectMake(x cordinate,y cordinate,linelenth,1)]; verticalLine.backgroundColor = [UIColor blackColor]; [self. view addSubView:verticalLine]; [verticalLine release]; 

你可以把它放到UIView中

 - (void)drawRect:(CGRect)rect { //// General Declarations CGContextRef context = UIGraphicsGetCurrentContext(); //// Shadow Declarations CGColorRef outerShadow = [UIColor blackColor].CGColor; CGSize outerShadowOffset = CGSizeMake(0, 1); CGFloat outerShadowBlurRadius = 2; //// Abstracted Graphic Attributes CGRect rectangleFrame = CGRectMake(0, 0, self.frame.size.width, 3); //// Rectangle Drawing UIBezierPath* rectanglePath = [UIBezierPath bezierPathWithRect: rectangleFrame]; [[UIColor lightGrayColor] setFill]; [rectanglePath fill]; ////// Rectangle Inner Shadow CGRect rectangleBorderRect = CGRectInset([rectanglePath bounds], -outerShadowBlurRadius, -outerShadowBlurRadius); rectangleBorderRect = CGRectOffset(rectangleBorderRect, -outerShadowOffset.width, -outerShadowOffset.height); rectangleBorderRect = CGRectInset(CGRectUnion(rectangleBorderRect, [rectanglePath bounds]), -1, -1); UIBezierPath* rectangleNegativePath = [UIBezierPath bezierPathWithRect: rectangleBorderRect]; [rectangleNegativePath appendPath: rectanglePath]; rectangleNegativePath.usesEvenOddFillRule = YES; CGContextSaveGState(context); { CGFloat xOffset = outerShadowOffset.width + round(rectangleBorderRect.size.width); CGFloat yOffset = outerShadowOffset.height; CGContextSetShadowWithColor(context, CGSizeMake(xOffset + copysign(0.1, xOffset), yOffset + copysign(0.1, yOffset)), outerShadowBlurRadius, outerShadow); [rectanglePath addClip]; CGAffineTransform transform = CGAffineTransformMakeTranslation(-round(rectangleBorderRect.size.width), 0); [rectangleNegativePath applyTransform: transform]; [[UIColor grayColor] setFill]; [rectangleNegativePath fill]; } CGContextRestoreGState(context); }