如何在UIView的顶部添加边框


Answers:


200

我在这里考虑继承UIView和覆盖drawRect过度杀伤。为什么不添加扩展UIView并添加边框子视图?

@discardableResult
func addBorders(edges: UIRectEdge,
                color: UIColor,
                inset: CGFloat = 0.0,
                thickness: CGFloat = 1.0) -> [UIView] {

    var borders = [UIView]()

    @discardableResult
    func addBorder(formats: String...) -> UIView {
        let border = UIView(frame: .zero)
        border.backgroundColor = color
        border.translatesAutoresizingMaskIntoConstraints = false
        addSubview(border)
        addConstraints(formats.flatMap {
            NSLayoutConstraint.constraints(withVisualFormat: $0,
                                           options: [],
                                           metrics: ["inset": inset, "thickness": thickness],
                                           views: ["border": border]) })
        borders.append(border)
        return border
    }


    if edges.contains(.top) || edges.contains(.all) {
        addBorder(formats: "V:|-0-[border(==thickness)]", "H:|-inset-[border]-inset-|")
    }

    if edges.contains(.bottom) || edges.contains(.all) {
        addBorder(formats: "V:[border(==thickness)]-0-|", "H:|-inset-[border]-inset-|")
    }

    if edges.contains(.left) || edges.contains(.all) {
        addBorder(formats: "V:|-inset-[border]-inset-|", "H:|-0-[border(==thickness)]")
    }

    if edges.contains(.right) || edges.contains(.all) {
        addBorder(formats: "V:|-inset-[border]-inset-|", "H:[border(==thickness)]-0-|")
    }

    return borders
}

    // Usage:         
    view.addBorder(edges: [.all]) // All with default arguments 
    view.addBorder(edges: [.top], color: .green) // Just Top, green, default thickness
    view.addBorder(edges: [.left, .right, .bottom], color: .red, thickness: 3) // All except Top, red, thickness 3

使用此代码,您也不必绑定到子类,您可以将其应用于继承自它的任何东西UIView-在项目中可重用,以及其他任何用途。将其他参数传递给您的方法以定义其他颜色和宽度。很多选择。


4
唯一的缺点是它无法调整大小。
Peter DeWeese 2014年

2
可以使用UIView并添加自动布局约束。相同的原则。
亚当·怀特

1
@PeterDeWeese这也不是缺点-如果您想控制边框的大小,您所需要做的就是:-(void)addUpperBorderWithSize:(CGFloat)size然后在函数中用参数替换常量。其他参数(例如颜色)也是如此。
o.shnn 2014年

1
@AdamWaite,此自动布局变体看起来非常好。谢谢 !
manonthemoon

2
感谢分享,我做一个版本的Objective-C,支持自动布局约束的位置
Itachi

99

为亚当·韦特(Adam Waite)的原始帖子以及多个编辑添加了圆角功能

重要提示:请不要忘记在调用前面提到的“ addborder”之前添加“ label.layoutIfNeeded()”

注意:我仅在UILabels上进行了测试。

扩展名CALayer {

enum BorderSide {
    case top
    case right
    case bottom
    case left
    case notRight
    case notLeft
    case topAndBottom
    case all
}

enum Corner {
    case topLeft
    case topRight
    case bottomLeft
    case bottomRight
}

func addBorder(side: BorderSide, thickness: CGFloat, color: CGColor, maskedCorners: CACornerMask? = nil) {
    var topWidth = frame.size.width; var bottomWidth = topWidth
    var leftHeight = frame.size.height; var rightHeight = leftHeight

    var topXOffset: CGFloat = 0; var bottomXOffset: CGFloat = 0
    var leftYOffset: CGFloat = 0; var rightYOffset: CGFloat = 0

    // Draw the corners and set side offsets
    switch maskedCorners {
    case [.layerMinXMinYCorner, .layerMaxXMinYCorner]: // Top only
        addCorner(.topLeft, thickness: thickness, color: color)
        addCorner(.topRight, thickness: thickness, color: color)
        topWidth -= cornerRadius*2
        leftHeight -= cornerRadius; rightHeight -= cornerRadius
        topXOffset = cornerRadius; leftYOffset = cornerRadius; rightYOffset = cornerRadius

    case [.layerMinXMaxYCorner, .layerMaxXMaxYCorner]: // Bottom only
        addCorner(.bottomLeft, thickness: thickness, color: color)
        addCorner(.bottomRight, thickness: thickness, color: color)
        bottomWidth -= cornerRadius*2
        leftHeight -= cornerRadius; rightHeight -= cornerRadius
        bottomXOffset = cornerRadius

    case [.layerMinXMinYCorner, .layerMinXMaxYCorner]: // Left only
        addCorner(.topLeft, thickness: thickness, color: color)
        addCorner(.bottomLeft, thickness: thickness, color: color)
        topWidth -= cornerRadius; bottomWidth -= cornerRadius
        leftHeight -= cornerRadius*2
        leftYOffset = cornerRadius; topXOffset = cornerRadius; bottomXOffset = cornerRadius;

    case [.layerMaxXMinYCorner, .layerMaxXMaxYCorner]: // Right only
        addCorner(.topRight, thickness: thickness, color: color)
        addCorner(.bottomRight, thickness: thickness, color: color)
        topWidth -= cornerRadius; bottomWidth -= cornerRadius
        rightHeight -= cornerRadius*2
        rightYOffset = cornerRadius

    case [.layerMaxXMinYCorner, .layerMaxXMaxYCorner,  // All
          .layerMinXMaxYCorner, .layerMinXMinYCorner]:
        addCorner(.topLeft, thickness: thickness, color: color)
        addCorner(.topRight, thickness: thickness, color: color)
        addCorner(.bottomLeft, thickness: thickness, color: color)
        addCorner(.bottomRight, thickness: thickness, color: color)
        topWidth -= cornerRadius*2; bottomWidth -= cornerRadius*2
        topXOffset = cornerRadius; bottomXOffset = cornerRadius
        leftHeight -= cornerRadius*2; rightHeight -= cornerRadius*2
        leftYOffset = cornerRadius; rightYOffset = cornerRadius

    default: break
    }

    // Draw the sides
    switch side {
    case .top:
        addLine(x: topXOffset, y: 0, width: topWidth, height: thickness, color: color)

    case .right:
        addLine(x: frame.size.width - thickness, y: rightYOffset, width: thickness, height: rightHeight, color: color)

    case .bottom:
        addLine(x: bottomXOffset, y: frame.size.height - thickness, width: bottomWidth, height: thickness, color: color)

    case .left:
        addLine(x: 0, y: leftYOffset, width: thickness, height: leftHeight, color: color)

    // Multiple Sides
    case .notRight:
        addLine(x: topXOffset, y: 0, width: topWidth, height: thickness, color: color)
        addLine(x: 0, y: leftYOffset, width: thickness, height: leftHeight, color: color)
        addLine(x: bottomXOffset, y: frame.size.height - thickness, width: bottomWidth, height: thickness, color: color)

    case .notLeft:
        addLine(x: topXOffset, y: 0, width: topWidth, height: thickness, color: color)
        addLine(x: frame.size.width - thickness, y: rightYOffset, width: thickness, height: rightHeight, color: color)
        addLine(x: bottomXOffset, y: frame.size.height - thickness, width: bottomWidth, height: thickness, color: color)

    case .topAndBottom:
        addLine(x: topXOffset, y: 0, width: topWidth, height: thickness, color: color)
        addLine(x: bottomXOffset, y: frame.size.height - thickness, width: bottomWidth, height: thickness, color: color)

    case .all:
        addLine(x: topXOffset, y: 0, width: topWidth, height: thickness, color: color)
        addLine(x: frame.size.width - thickness, y: rightYOffset, width: thickness, height: rightHeight, color: color)
        addLine(x: bottomXOffset, y: frame.size.height - thickness, width: bottomWidth, height: thickness, color: color)
        addLine(x: 0, y: leftYOffset, width: thickness, height: leftHeight, color: color)
    }
}

private func addLine(x: CGFloat, y: CGFloat, width: CGFloat, height: CGFloat, color: CGColor) {
    let border = CALayer()
    border.frame = CGRect(x: x, y: y, width: width, height: height)
    border.backgroundColor = color
    addSublayer(border)
}

private func addCorner(_ corner: Corner, thickness: CGFloat, color: CGColor) {
    // Set default to top left
    let width = frame.size.width; let height = frame.size.height
    var x = cornerRadius
    var startAngle: CGFloat = .pi; var endAngle: CGFloat = .pi*3/2

    switch corner {
    case .bottomLeft: startAngle = .pi/2; endAngle = .pi

    case .bottomRight:
        x = width - cornerRadius
        startAngle = 0; endAngle = .pi/2

    case .topRight:
        x = width - cornerRadius
        startAngle = .pi*3/2; endAngle = 0

    default: break
    }

    let cornerPath = UIBezierPath(arcCenter: CGPoint(x: x, y: height / 2),
                                  radius: cornerRadius - thickness,
                                  startAngle: startAngle,
                                  endAngle: endAngle,
                                  clockwise: true)

    let cornerShape = CAShapeLayer()
    cornerShape.path = cornerPath.cgPath
    cornerShape.lineWidth = thickness
    cornerShape.strokeColor = color
    cornerShape.fillColor = nil
    addSublayer(cornerShape)
}

}


4
更改CGRectMake签名和每个Swift 3的CGColor之后,由于某些原因,该代码无法在Swift 3上运行
。– EmbCoder

这里有一个很好的文章medium.com/swift-programming/...你需要斯威夫特3.做什么的会谈
米卡蒙托亚

2
运气快点实现这一点有运气吗?
Marquavious Draggon '17

7
要使其正常工作,您需要view.layoutIfNeeded()在调用之前添加右键view.layer.addBorder(...)。然后在Swift 3
Adam Studenic

工作正常。用这种方法添加线override func viewDidLayoutSubviews()
Antony Raphel

60

对我来说,最好的方法是在UIView上使用类别,而adding views不是CALayers,因此我们可以take advantage of AutoresizingMasks确保边框和Superview 一起调整大小。

目标C

- (void)addTopBorderWithColor:(UIColor *)color andWidth:(CGFloat) borderWidth {
    UIView *border = [UIView new];
    border.backgroundColor = color;
    [border setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleBottomMargin];
    border.frame = CGRectMake(0, 0, self.frame.size.width, borderWidth);
    [self addSubview:border];
}

- (void)addBottomBorderWithColor:(UIColor *)color andWidth:(CGFloat) borderWidth {
    UIView *border = [UIView new];
    border.backgroundColor = color;
    [border setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
    border.frame = CGRectMake(0, self.frame.size.height - borderWidth, self.frame.size.width, borderWidth);
    [self addSubview:border];
}

- (void)addLeftBorderWithColor:(UIColor *)color andWidth:(CGFloat) borderWidth {
    UIView *border = [UIView new];
    border.backgroundColor = color;
    border.frame = CGRectMake(0, 0, borderWidth, self.frame.size.height);
    [border setAutoresizingMask:UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleRightMargin];
    [self addSubview:border];
}

- (void)addRightBorderWithColor:(UIColor *)color andWidth:(CGFloat) borderWidth {
    UIView *border = [UIView new];
    border.backgroundColor = color;
    [border setAutoresizingMask:UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleLeftMargin];
    border.frame = CGRectMake(self.frame.size.width - borderWidth, 0, borderWidth, self.frame.size.height);
    [self addSubview:border];
}

斯威夫特5

func addTopBorder(with color: UIColor?, andWidth borderWidth: CGFloat) {
    let border = UIView()
    border.backgroundColor = color
    border.autoresizingMask = [.flexibleWidth, .flexibleBottomMargin]
    border.frame = CGRect(x: 0, y: 0, width: frame.size.width, height: borderWidth)
    addSubview(border)
}

func addBottomBorder(with color: UIColor?, andWidth borderWidth: CGFloat) {
    let border = UIView()
    border.backgroundColor = color
    border.autoresizingMask = [.flexibleWidth, .flexibleTopMargin]
    border.frame = CGRect(x: 0, y: frame.size.height - borderWidth, width: frame.size.width, height: borderWidth)
    addSubview(border)
}

func addLeftBorder(with color: UIColor?, andWidth borderWidth: CGFloat) {
    let border = UIView()
    border.backgroundColor = color
    border.frame = CGRect(x: 0, y: 0, width: borderWidth, height: frame.size.height)
    border.autoresizingMask = [.flexibleHeight, .flexibleRightMargin]
    addSubview(border)
}

func addRightBorder(with color: UIColor?, andWidth borderWidth: CGFloat) {
    let border = UIView()
    border.backgroundColor = color
    border.autoresizingMask = [.flexibleHeight, .flexibleLeftMargin]
    border.frame = CGRect(x: frame.size.width - borderWidth, y: 0, width: borderWidth, height: frame.size.height)
    addSubview(border)
}

7
到目前为止,这是解决此问题的最佳方法之一。大多数其他解决方案提供的功能都不支持视图更改(因此不支持设备旋转或拆分视图)。这一个。
2015年

1
如何适应圆角?
ntaj

29

斯威夫特3.0

斯威夫特4.1

extension CALayer {

  func addBorder(edge: UIRectEdge, color: UIColor, thickness: CGFloat) {

    let border = CALayer()

    switch edge {
    case UIRectEdge.top:
        border.frame = CGRect(x: 0, y: 0, width: frame.width, height: thickness)

    case UIRectEdge.bottom:
        border.frame = CGRect(x:0, y: frame.height - thickness, width: frame.width, height:thickness)

    case UIRectEdge.left:
        border.frame = CGRect(x:0, y:0, width: thickness, height: frame.height)

    case UIRectEdge.right:
        border.frame = CGRect(x: frame.width - thickness, y: 0, width: thickness, height: frame.height)

    default: do {}
    }

    border.backgroundColor = color.cgColor

    addSublayer(border)
 }
}

1
当视图调整大小(例如方向更改)时,此功能不起作用。
内斯特

如果您使用的是基于框架的布局,则必须实现layoutSubviews并重新计算其中的所有子视图(或子层)框架
trapper

22

子类UIViewdrawRect:在您的子类中实现,例如:

目标c

- (void)drawRect:(CGRect)rect {
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextMoveToPoint(context, CGRectGetMinX(rect), CGRectGetMinY(rect));
    CGContextAddLineToPoint(context, CGRectGetMaxX(rect), CGRectGetMinY(rect));
    CGContextSetStrokeColorWithColor(context, [[UIColor redColor] CGColor] );
    CGContextSetLineWidth(context, 2.0);
    CGContextStrokePath(context);
}

斯威夫特4

override func draw(_ rect: CGRect) {

    let cgContext = UIGraphicsGetCurrentContext()
    cgContext?.move(to: CGPoint(x: rect.minX, y: rect.minY))
    cgContext?.addLine(to: CGPoint(x: rect.maxX, y: rect.minY))
    cgContext?.setStrokeColor(UIColor.red.cgColor)
    cgContext?.setLineWidth(2.0)
    cgContext?.strokePath()
}

这将绘制2像素的红线作为顶部边框。您提到的所有其他变体对读者来说都是一个琐碎的练习。

建议使用《Quartz 2D编程指南》


这是唯一的方法吗?因此,如果我需要创建一个带有顶部边框的视图,另一个带有底部边框的视图,以及其他视图……我的意思是总是一个带有一个或两个边框的特定视图,那么我将不得不为每种特定情况创建一个子类。 ??? 我不知道为增加边框而创建类是否真的很棒……
manonthemoon 2013年

1
不,考虑一下。您的UIView子类可以具有一个确定drawRect:绘制边框的属性。可以使用定义此属性,NS_OPTIONS以便定义类似于UIViewAutoresizing位掩码的位掩码。如果-由于某种原因-您确实强烈反对子类化,UIView则只需添加一个小1-2像素高(或宽)的子视图,并为其提供任何您想要模拟边框的尺寸即可。
FluffulousChimp

大家好,我制作了一个受此代码启发的Swift子类,希望您喜欢它:gist.github.com/asiviero/4f52ab7dea7d9252a64c
asiviero

19

如果有人需要,为所选答案编码。

注意:这不适用于自动布局(也就是将设备旋转到横向等)。

首先定义一个厚度:

NSInteger borderThickness = 1;

然后只需复制使用任何这些或全部设置您要设置的边框即可。

上边框

UIView *topBorder = [UIView new];
topBorder.backgroundColor = [UIColor lightGrayColor];
topBorder.frame = CGRectMake(0, 0, myView.frame.size.width, borderThickness);
[myView addSubview:topBorder];

底边框

UIView *bottomBorder = [UIView new];
bottomBorder.backgroundColor = [UIColor lightGrayColor];
bottomBorder.frame = CGRectMake(0, myView.frame.size.height - borderThickness, myView.frame.size.width, borderThickness);
[myView addSubview:bottomBorder];

左边框

UIView *leftBorder = [UIView new];
leftBorder.backgroundColor = [UIColor lightGrayColor];
leftBorder.frame = CGRectMake(0, 0, borderThickness, myView.frame.size.height);
[myView addSubview:leftBorder];

右边界

UIView *rightBorder = [UIView new];
rightBorder.backgroundColor = [UIColor lightGrayColor];
rightBorder.frame = CGRectMake(myView.frame.size.width - borderThickness, 0, borderThickness, myView.frame.size.height);
[myView addSubview:rightBorder];

简便易用的解决方案...与裸CALayer相比,具有UIView开销
Soberman 2015年

阅读完所有其他解决方案后,我想我也只会添加一个小视图。所有这些都是为了边界!该解决方案仅需要几个引脚即可在自动布局中工作。轻松解决问题的方法。
noobsmcgoobs

谢谢,我在上面添加了一条注释,以便编码人员仅在其应用不会旋转时才能使用。
特拉维斯M.16年

15

老问题了,但是仍然缺少带有运行时边界调整的自动布局解决方案。

borders(for: [.left, .bottom], width: 2, color: .red)

以下UIView扩展将仅在给定的边缘上添加边框。如果在运行时更改边缘,则边框将相应调整。

extension UIView {
    func borders(for edges:[UIRectEdge], width:CGFloat = 1, color: UIColor = .black) {

        if edges.contains(.all) {
            layer.borderWidth = width
            layer.borderColor = color.cgColor
        } else {
            let allSpecificBorders:[UIRectEdge] = [.top, .bottom, .left, .right]

            for edge in allSpecificBorders {
                if let v = viewWithTag(Int(edge.rawValue)) {
                    v.removeFromSuperview()
                }

                if edges.contains(edge) {
                    let v = UIView()
                    v.tag = Int(edge.rawValue)
                    v.backgroundColor = color
                    v.translatesAutoresizingMaskIntoConstraints = false
                    addSubview(v)

                    var horizontalVisualFormat = "H:"
                    var verticalVisualFormat = "V:"

                    switch edge {
                    case UIRectEdge.bottom:
                        horizontalVisualFormat += "|-(0)-[v]-(0)-|"
                        verticalVisualFormat += "[v(\(width))]-(0)-|"
                    case UIRectEdge.top:
                        horizontalVisualFormat += "|-(0)-[v]-(0)-|"
                        verticalVisualFormat += "|-(0)-[v(\(width))]"
                    case UIRectEdge.left:
                        horizontalVisualFormat += "|-(0)-[v(\(width))]"
                        verticalVisualFormat += "|-(0)-[v]-(0)-|"
                    case UIRectEdge.right:
                        horizontalVisualFormat += "[v(\(width))]-(0)-|"
                        verticalVisualFormat += "|-(0)-[v]-(0)-|"
                    default:
                        break
                    }

                    self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: horizontalVisualFormat, options: .directionLeadingToTrailing, metrics: nil, views: ["v": v]))
                    self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: verticalVisualFormat, options: .directionLeadingToTrailing, metrics: nil, views: ["v": v]))
                }
            }
        }
    }
}

13

迅捷版:

var myView = UIView(frame: CGRect(x: 100, y: 100, width: 100, height: 100))
myView.backgroundColor = UIColor.yellowColor() 

var border = CALayer()
border.backgroundColor = UIColor.lightGrayColor()
border.frame = CGRect(x: 0, y: 0, width: myView.frame.width, height: 0.5)

myView.layer.addSublayer(border)

编辑:有关更新的版本,请在此处查看我的仓库:https : //github.com/goktugyil/EZSwiftExtensions/blob/master/Sources/UIViewExtensions.swift

看一下addBorder部分


4

我同时接受了亚当·怀特(Adam Waite)和保罗(Pauls)的答案,并将它们组合在一起。我还添加了将选定边通过管道连接在一起的可能性,因此您只需要像下面这样调用一个函数:

[self.view addBordersToEdge:(UIRectEdgeLeft|UIRectEdgeRight)
                  withColor:[UIColor grayColor]
                   andWidth:1.0];

或者:

[self.view addBordersToEdge:(UIRectEdgeAll)
                  withColor:[UIColor grayColor]
                   andWidth:1.0];

您需要实现的是UIView上的类别,如其他答案中建议的那样,使用以下实现:

- (void)addBordersToEdge:(UIRectEdge)edge withColor:(UIColor *)color andWidth:(CGFloat) borderWidth {
    if (edge & UIRectEdgeTop) {
        UIView *border = [UIView new];
        border.backgroundColor = color;
        [border setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleBottomMargin];
        border.frame = CGRectMake(0, 0, self.frame.size.width, borderWidth);
        [self addSubview:border];
    }

    if (edge & UIRectEdgeLeft) {
        UIView *border = [UIView new];
        border.backgroundColor = color;
        border.frame = CGRectMake(0, 0, borderWidth, self.frame.size.height);
        [border setAutoresizingMask:UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleRightMargin];
        [self addSubview:border];
    }

    if (edge & UIRectEdgeBottom) {
        UIView *border = [UIView new];
        border.backgroundColor = color;
        [border setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
        border.frame = CGRectMake(0, self.frame.size.height - borderWidth, self.frame.size.width, borderWidth);
        [self addSubview:border];
    }

    if (edge & UIRectEdgeRight) {
        UIView *border = [UIView new];
        border.backgroundColor = color;
        [border setAutoresizingMask:UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleLeftMargin];
        border.frame = CGRectMake(self.frame.size.width - borderWidth, 0, borderWidth, self.frame.size.height);
        [self addSubview:border];
    }
}

4

// MARK:-添加LeftBorder以供查看

(void)prefix_addLeftBorder:(UIView *) viewName
{
    CALayer *leftBorder = [CALayer layer];
    leftBorder.backgroundColor = [UIColor colorWithRed:221/255.0f green:221/255.0f blue:221/255.0f alpha:1.0f].CGColor;
    leftBorder.frame = CGRectMake(0,0,1.0,viewName.frame.size.height);
    [viewName.layer addSublayer:leftBorder];
}

// MARK:-为视图添加RightBorder

(void)prefix_addRightBorder:(UIView *) viewName
{
    CALayer *rightBorder = [CALayer layer];
    rightBorder.backgroundColor = [UIColor colorWithRed:221/255.0f green:221/255.0f blue:221/255.0f alpha:1.0f].CGColor;
    rightBorder.frame = CGRectMake(viewName.frame.size.width - 1.0,0,1.0,viewName.frame.size.height);
    [viewName.layer addSublayer:rightBorder];
}

// MARK:-添加底部边框以供查看

(void)prefix_addbottomBorder:(UIView *) viewName
{
    CALayer *bottomBorder = [CALayer layer];
    bottomBorder.backgroundColor = [UIColor colorWithRed:221/255.0f green:221/255.0f blue:221/255.0f alpha:1.0f].CGColor;
    bottomBorder.frame = CGRectMake(0,viewName.frame.size.height - 1.0,viewName.frame.size.width,1.0);
    [viewName.layer addSublayer:bottomBorder];
}

4

Swift 4.2和AutoLayout

我经历了提供的解决方案。许多是基于框架的这是一个与AutoLayout一起使用的简单扩展-使用View而不是Layer以确保我们可以使用AutoLayout-具有4个约束的单个子视图

用法如下:

self.addBorder(.bottom, color: .lightGray, thickness: 0.5)


extension UIView {
    func addBorder(_ edge: UIRectEdge, color: UIColor, thickness: CGFloat) {
        let subview = UIView()
        subview.translatesAutoresizingMaskIntoConstraints = false
        subview.backgroundColor = color
        self.addSubview(subview)
        switch edge {
        case .top, .bottom:
            subview.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 0).isActive = true
            subview.rightAnchor.constraint(equalTo: self.rightAnchor, constant: 0).isActive = true
            subview.heightAnchor.constraint(equalToConstant: thickness).isActive = true
            if edge == .top {
                subview.topAnchor.constraint(equalTo: self.topAnchor, constant: 0).isActive = true
            } else {
                subview.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: 0).isActive = true
            }
        case .left, .right:
            subview.topAnchor.constraint(equalTo: self.topAnchor, constant: 0).isActive = true
            subview.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: 0).isActive = true
            subview.widthAnchor.constraint(equalToConstant: thickness).isActive = true
            if edge == .left {
                subview.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 0).isActive = true
            } else {
                subview.rightAnchor.constraint(equalTo: self.rightAnchor, constant: 0).isActive = true
            }
        default:
            break
        }
    }
}

3

我对Dan的答案进行了一些更改,以便可以使用一个命令将边框添加到多个边缘:

infoView.addBorder(toEdges: [.left, .bottom, .right], color: borderColor, thickness: 1)

这是完整的代码:

extension UIView {
    func addBorder(toEdges edges: UIRectEdge, color: UIColor, thickness: CGFloat) {

        func addBorder(toEdge edges: UIRectEdge, color: UIColor, thickness: CGFloat) {
            let border = CALayer()
            border.backgroundColor = color.cgColor

            switch edges {
            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
            }

            layer.addSublayer(border)
        }

        if edges.contains(.top) || edges.contains(.all) {
            addBorder(toEdge: .top, color: color, thickness: thickness)
        }

        if edges.contains(.bottom) || edges.contains(.all) {
            addBorder(toEdge: .bottom, color: color, thickness: thickness)
        }

        if edges.contains(.left) || edges.contains(.all) {
            addBorder(toEdge: .left, color: color, thickness: thickness)
        }

        if edges.contains(.right) || edges.contains(.all) {
            addBorder(toEdge: .right, color: color, thickness: thickness)
        }
    }
}

2

基于NSBum的答案,我采用了类似的方法并创建了这个简单的UIView子类,以便它可以在Interface Builder中工作并可以在约束条件下工作:github链接
通过使用CGContextFillRect而不是CGContextStrokePath,我能够以可预测的方式将线条完全固定在内部视图的边界。

这是关于它的我的博客文章:http : //natrosoft.com/?p=55

-基本上只需在Interface Builder中放入UIView,并将其类类型更改为NAUIViewWithBorders。
-然后在VC的viewDidLoad中执行以下操作:

/* For a top border only ———————————————- */
self.myBorderView.borderColorTop = [UIColor redColor];
self.myBorderView..borderWidthsAll = 1.0f;

/* For borders with different colors and widths ————————— */
self.myBorderView.borderWidths = UIEdgeInsetsMake(2.0, 4.0, 6.0, 8.0);
self.myBorderView.borderColorTop = [UIColor blueColor];
self.myBorderView.borderColorRight = [UIColor redColor];
self.myBorderView.borderColorBottom = [UIColor greenColor];
self.myBorderView.borderColorLeft = [UIColor darkGrayColor];

这是指向.m文件的直接链接,因此您可以查看实现。还有一个演示项目。希望这可以帮助某人:)



2
extension UIView {

    func addBorder(edge: UIRectEdge, color: UIColor, borderWidth: CGFloat) {

        let seperator = UIView()
        self.addSubview(seperator)
        seperator.translatesAutoresizingMaskIntoConstraints = false

        seperator.backgroundColor = color

        if edge == .top || edge == .bottom
        {
            seperator.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 0).isActive = true
            seperator.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: 0).isActive = true
            seperator.heightAnchor.constraint(equalToConstant: borderWidth).isActive = true

            if edge == .top
            {
                seperator.topAnchor.constraint(equalTo: self.topAnchor, constant: 0).isActive = true
            }
            else
            {
                seperator.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: 0).isActive = true
            }
        }
        else if edge == .left || edge == .right
        {
            seperator.topAnchor.constraint(equalTo: self.topAnchor, constant: 0).isActive = true
            seperator.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: 0).isActive = true
            seperator.widthAnchor.constraint(equalToConstant: borderWidth).isActive = true

            if edge == .left
            {
                seperator.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 0).isActive = true
            }
            else
            {
                seperator.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: 0).isActive = true
            }
        }
    }

}

2

这是一个简单的解决方案。在上添加标签UIView,清除标签上的文本,然后将标签背景色设置为边框颜色。将(x,y)标签的原点设置(x,y)为视图的原点。并将标签的宽度UIView设置为您的宽度,将高度设置为1或2(因为边框高度位于顶部UIView)。那应该可以解决问题。


28
那么,没有标签的意义可能就是另一个UIView
maor10

1
这并不能真正回答仅向uiview添加顶部边框的问题。这是一个快速修复程序,可能不适用于更复杂的问题。
simon_smiley 2014年


2

Swift 3版本

extension UIView {
    enum ViewSide {
        case Top, Bottom, Left, Right
    }

    func addBorder(toSide side: ViewSide, withColor color: UIColor, andThickness thickness: CGFloat) {

        let border = CALayer()
        border.backgroundColor = color.cgColor

        switch side {
        case .Top:
            border.frame = CGRect(x: 0, y: 0, width: frame.size.width, height: thickness)
        case .Bottom:
            border.frame = CGRect(x: 0, y: frame.size.height - thickness, width: frame.size.width, height: thickness)
        case .Left:
            border.frame = CGRect(x: 0, y: 0, width: thickness, height: frame.size.height)
        case .Right:
            border.frame = CGRect(x: frame.size.width - thickness, y: 0, width: thickness, height: frame.size.height)
        }

        layer.addSublayer(border)
    }
}

为了设置相应的边框,您应该重写viewDidLayoutSubviews()方法:

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    yourView.addBorder(toSide: UIView.ViewSide.Top, withColor: UIColor.lightGray, andThickness: 1)

每当布局得到更新时,它将调用“ addSublayer”吗?
byJeevan

1

只需在此处发布即可帮助寻找边框的人。我在接受的答案中做了一些更改,这里仅将标签留边框的左边。更改了宽度(UIRectEdge.TopCGRectGetHeight(self.frame)到)CGRectGetWidth(self.frame)和从到的情况UIRectEdge.BottomUIScreen.mainScreen().bounds.widthCGRectGetWidth(self.frame)正确更改边框)。使用Swift 2。

最后,扩展名是:

extension CALayer {

func addBorder(edge: UIRectEdge, color: UIColor, thickness: CGFloat) {

    let border = CALayer();

    switch edge {
    case UIRectEdge.Top:
        border.frame = CGRectMake(0, 0, CGRectGetWidth(self.frame), thickness); 
        break
    case UIRectEdge.Bottom:
        border.frame = CGRectMake(0, CGRectGetHeight(self.frame) - thickness, CGRectGetWidth(self.frame), thickness)
        break
    case UIRectEdge.Left:
        border.frame = CGRectMake(0, 0, thickness, CGRectGetHeight(self.frame))
        break
    case UIRectEdge.Right:
        border.frame = CGRectMake(CGRectGetWidth(self.frame) - thickness, 0, thickness, CGRectGetHeight(self.frame))
        break
    default:
        break
    }

    border.backgroundColor = color.CGColor;

    self.addSublayer(border)
}

}

1

万一有人需要Xamarin版本:

public static class UIUtils
{
    public static void AddBorder(this CALayer cALayer, UIRectEdge edge, UIColor color, float thickness)
    {

        var border = new CALayer();
        switch (edge) 
        {
            case UIRectEdge.Top:
                border.Frame = new CGRect(0, 0, cALayer.Frame.Width, height: thickness);
                break;
            case UIRectEdge.Bottom:
                border.Frame = new CGRect(0, cALayer.Frame.Height - thickness, width: cALayer.Frame.Width, height: thickness);
                break;
            case UIRectEdge.Left:
                border.Frame = new CGRect(0, 0, width: thickness, height: cALayer.Frame.Height);
                break;
            case UIRectEdge.Right:
                border.Frame = new CGRect(cALayer.Frame.Width - thickness, y: 0, width: thickness, height: cALayer.Frame.Height);
                break;
            default: break;
        }
        border.BackgroundColor = color.CGColor;
        cALayer.AddSublayer(border);
    }
}

1

这是Pauls答案的Swift 4版本

func addTopBorder(color: UIColor, thickness: CGFloat) {
    let border = UIView()
    border.backgroundColor = color
    border.autoresizingMask = [.flexibleWidth, .flexibleBottomMargin]
    border.frame = CGRect(x: 0, y: 0, width: frame.size.width, height: thickness)
    addSubview(border)
}

func addBottomBorder(color: UIColor, thickness: CGFloat) {
    let border = UIView()
    border.backgroundColor = color
    border.autoresizingMask = [.flexibleWidth, .flexibleTopMargin]
    border.frame = CGRect(x: 0, y: frame.size.height - thickness, width: frame.size.width, height: thickness)
    addSubview(border)
}

func addLeftBorder(color: UIColor, thickness: CGFloat) {
    let border = UIView()
    border.backgroundColor = color
    border.autoresizingMask = [.flexibleHeight, .flexibleRightMargin]
    border.frame = CGRect(x: 0, y: 0, width: thickness, height: frame.size.height)
    addSubview(border)
}

func addRightBorder(color: UIColor, thickness: CGFloat) {
    let border = UIView()
    border.backgroundColor = color
    border.autoresizingMask = [.flexibleHeight, .flexibleLeftMargin]
    border.frame = CGRect(x: frame.size.width - thickness, y: 0, width: thickness, height: frame.size.height)
    addSubview(border)
}

1

受@Addison的启发,由于他使用了SnapKit和CocoaLumberjack,因此我在不使用任何第三方框架的情况下重写了该扩展。

与@Addisons方法一样,我也要删除以前添加的边框,因此此实现应与表单元格和集合单元格等可重用视图一起使用。

fileprivate class BorderView: UIView {} // dummy class to help us differentiate among border views and other views
                                        // to enabling us to remove existing borders and place new ones

extension UIView {

    func setBorders(toEdges edges: [UIRectEdge], withColor color: UIColor, inset: CGFloat = 0, thickness: CGFloat) {
        // Remove existing edges
        for view in subviews {
            if view is BorderView {
                view.removeFromSuperview()
            }
        }
        // Add new edges
        if edges.contains(.all) {
            addSidedBorder(toEdge: [.left,.right, .top, .bottom], withColor: color, inset: inset, thickness: thickness)
        }
        if edges.contains(.left) {
            addSidedBorder(toEdge: [.left], withColor: color, inset: inset, thickness: thickness)
        }
        if edges.contains(.right) {
            addSidedBorder(toEdge: [.right], withColor: color, inset: inset, thickness: thickness)
        }
        if edges.contains(.top) {
            addSidedBorder(toEdge: [.top], withColor: color, inset: inset, thickness: thickness)
        }
        if edges.contains(.bottom) {
            addSidedBorder(toEdge: [.bottom], withColor: color, inset: inset, thickness: thickness)
        }
    }

    private func addSidedBorder(toEdge edges: [RectangularEdges], withColor color: UIColor, inset: CGFloat = 0, thickness: CGFloat) {
        for edge in edges {
            let border = BorderView(frame: .zero)
            border.backgroundColor = color
            addSubview(border)
            border.translatesAutoresizingMaskIntoConstraints = false
            switch edge {
            case .left:
                NSLayoutConstraint.activate([
                border.leftAnchor.constraint(equalTo: self.leftAnchor, constant: inset),
                    border.topAnchor.constraint(equalTo: self.topAnchor, constant: inset),
                    border.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: -inset),
                    NSLayoutConstraint(item: border, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .width, multiplier: 1, constant: thickness) ])
            case .right:
                NSLayoutConstraint.activate([
                    border.rightAnchor.constraint(equalTo: self.rightAnchor, constant: -inset),
                    border.topAnchor.constraint(equalTo: self.topAnchor, constant: inset),
                    border.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: -inset),
                    NSLayoutConstraint(item: border, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .width, multiplier: 1, constant: thickness) ])
            case .top:
                NSLayoutConstraint.activate([
                    border.leftAnchor.constraint(equalTo: self.leftAnchor, constant: inset),
                    border.rightAnchor.constraint(equalTo: self.rightAnchor, constant: -inset),
                    border.topAnchor.constraint(equalTo: self.topAnchor, constant: inset),
                    NSLayoutConstraint(item: border, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1, constant: thickness) ])
            case .bottom:
                NSLayoutConstraint.activate([
                    border.leftAnchor.constraint(equalTo: self.leftAnchor, constant: inset),
                    border.rightAnchor.constraint(equalTo: self.rightAnchor, constant: -inset),
                    border.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: -inset),
                    NSLayoutConstraint(item: border, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1, constant: thickness) ])
            }
        }
    }

    private enum RectangularEdges {
        case left
        case right
        case top
        case bottom
    }
}

1

如果要从情节提要中进行构建,则最好在UIView有用的内容后面添加一个UIView...如果要在我的顶部创建边框UIView,只需将背景高度增加UIView边框宽度即可。同样可以做任何其他方面:)


0

就个人而言,我喜欢view + drawRect的子类,但这只是另一种解决方法(它的工作方式与@If Pollavith接受的答案相同):

可以将新的边界层设置为具有所需的任何尺寸。因此,就像@If Pollavith的答案一样,您将创建一个图层,使其高至您想要的高度,并达到您想要边框的视图的宽度。使用图层的框架定义将其放置在所需的位置,然后将其作为子图层添加到视图中。

作为参考,我自己的要求是在视图的左手边上放置一个边框(请不要剪切并粘贴此代码,而只是“因为它不会在视图的顶部放置边框” -修改下面的代码很简单):

    CALayer *leftBorder = [CALayer layer];
leftBorder.borderColor = [UIColor colorWithRed:0.0 green:91.0/255.0 blue:141.0/255.0 alpha:1.0].CGColor;
leftBorder.borderWidth = 1;
leftBorder.frame = CGRectMake(0, 0, 1.0, CGRectGetHeight(self.myTargetView.frame));
[self.myTargetView.layer addSublayer:leftBorder];

我猜想,这样做并做一个小的UIView或UILabel唯一的适度好处是CALayer应该是“轻量级”的,并且有很多有趣的观点(如观点)关于超越drawRect与使用CALayers(例如此处) :iOS:使用UIView的'drawRect:'相对于其层的滞后'drawLayer:inContext:')。

动物451

我喜欢蓝色。



0

DanShev答案转换为Swift 3

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: self.frame.width, height: thickness)
        break
    case .bottom:
        border.frame = CGRect(x: 0, y: self.frame.height - thickness, width: self.frame.width, height: thickness)
        break
    case .left:
        border.frame = CGRect(x: 0, y: 0, width: thickness, height: self.frame.height)
        break
    case .right:
        border.frame = CGRect(x: self.frame.width - thickness, y: 0, width: thickness, height: self.frame.height)
        break
    default:
        break
    }

    border.backgroundColor = color.cgColor;

    self.addSublayer(border)
}
}

0

对于C#中的Xamarin,我仅在添加子层时创建内联边框

  View.Layer.AddSublayer(new CALayer()
    {
        BackgroundColor = UIColor.Black.CGColor,
        Frame = new CGRect(0, 0, View.Frame.Width, 0.5f)
    });

您可以(根据其他人的建议)为底部,左侧和右侧边框进行排列。



0

注意:此处的大多数解决方案都不具有自适应性,因此无法调整大小。将会调整大小的解决方案将有大量使用大量CPU,对您的启动时间产生影响。

您可以在下面使用此解决方案。它适用于比图层更轻的UIBezierPaths,导致启动时间短。它易于使用,请参阅下面的说明。

class ResizeBorderView: UIView {
    var color = UIColor.white
    var lineWidth: CGFloat = 1
    var edges = [UIRectEdge](){
        didSet {
            setNeedsDisplay()
        }
    }
    override func draw(_ rect: CGRect) {
        if edges.contains(.top) || edges.contains(.all){
            let path = UIBezierPath()
            path.lineWidth = lineWidth
            color.setStroke()
            UIColor.blue.setFill()
            path.move(to: CGPoint(x: 0, y: 0 + lineWidth / 2))
            path.addLine(to: CGPoint(x: self.bounds.width, y: 0 + lineWidth / 2))
            path.stroke()
        }
        if edges.contains(.bottom) || edges.contains(.all){
            let path = UIBezierPath()
            path.lineWidth = lineWidth
            color.setStroke()
            UIColor.blue.setFill()
            path.move(to: CGPoint(x: 0, y: self.bounds.height - lineWidth / 2))
            path.addLine(to: CGPoint(x: self.bounds.width, y: self.bounds.height - lineWidth / 2))
            path.stroke()
        }
        if edges.contains(.left) || edges.contains(.all){
            let path = UIBezierPath()
            path.lineWidth = lineWidth
            color.setStroke()
            UIColor.blue.setFill()
            path.move(to: CGPoint(x: 0 + lineWidth / 2, y: 0))
            path.addLine(to: CGPoint(x: 0 + lineWidth / 2, y: self.bounds.height))
            path.stroke()
        }
        if edges.contains(.right) || edges.contains(.all){
            let path = UIBezierPath()
            path.lineWidth = lineWidth
            color.setStroke()
            UIColor.blue.setFill()
            path.move(to: CGPoint(x: self.bounds.width - lineWidth / 2, y: 0))
            path.addLine(to: CGPoint(x: self.bounds.width - lineWidth / 2, y: self.bounds.height))
            path.stroke()
        }
    }
}
  1. 将您的UIView的类设置为ResizeBorderView
  2. 通过在viewDidAppear方法中使用yourview.color和yourview.lineWidth设置颜色和线条宽度
  3. 设置边缘,例如:yourview.edges = [.right,.left]([.all])
  4. 享受快速入门和调整边框大小

0

用于在Swift中为UIView设置顶部边框和底部边框。

let topBorder = UIView(frame: CGRect(x: 0, y: 0, width: 10, height: 1))
topBorder.backgroundColor = UIColor.black
myView.addSubview(topBorder)

let bottomBorder = UIView(frame: CGRect(x: 0, y: myView.frame.size.height - 1, width: 10, height: 1))
bottomBorder.backgroundColor = UIColor.black
myView.addSubview(bottomBorder)

0

在Swift 4和3中

let borderThickness = 2
let topBorder = UIView()
topBorder.backgroundColor = UIColor.red
topBorder.frame = CGRect(x: 0, y: 0, width: 
                  Int(yourViewFromOutlet.frame.size.width), height: 
                  borderThickness)
yourViewFromOutlet.addSubview(topBorder)
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.