创建一条水平线

4th*_*ace 39 iphone cocoa-touch uiimageview uiimage

我有两个堆叠的标签.如果我想在它们之间使用水平线,除了使用带有UIImageView的图像之外还有其他方法吗?

Jas*_*ien 86

创建一个UIView,黑色背景为1像素高,320像素宽.

  • 这个答案让人不屑一顾.也许解释一下如何在Interface Builder中执行此操作? (14认同)
  • 这是一个10年前的问答。放手吧 (2认同)

Tom*_*ing 19

使用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];
Run Code Online (Sandbox Code Playgroud)


Pha*_*ast 13

虽然Jasarien的解决方案很简单,但它不能创建一个实际的1像素发际线,而是在2X设备上创建一个2像素宽的线.

我发现了一篇关于如何创建真正的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()
    }
}
Run Code Online (Sandbox Code Playgroud)


Mad*_*dhu 5

对于水平线

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

对于垂直线

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