代码之家  ›  专栏  ›  技术社区  ›  Abdulmoiz Ahmer

如何在iOS中向uiview添加上下边框?

  •  0
  • Abdulmoiz Ahmer  · 技术社区  · 6 年前

    enter image description here

    上面的边界就是我想要实现的。

    2 回复  |  直到 6 年前
        1
  •  2
  •   Shahzaib Qureshi    6 年前

    试试这个 -(void)addBottomBorderToView:(UIView *)view{ UIView *bottomBorder = [[UIView alloc]initWithFrame:CGRectMake(0,view.frame.size.height - 1, view.frame.size.width, 1)]; bottomBorder.backgroundColor = UIColor.darkGrayColor; [view addSubview:bottomBorder]; }

    Swift:

    func addBottomView(view : UIView){
    let bottomView = CGRect(0,view.frame.size.height-1,view.frame.size.width,1)
    bottomView.backgroundColor = UIColor.darkGrayColor
    view.addSubView(bottomView)
    

    }

        2
  •  4
  •   AtulParmar    6 年前

    尝试此代码,使用此代码可以设置顶部/按钮/左/右任何带颜色和粗细的边框。

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

    使用以下代码指定视图边框

    view.layer.addBorder(edge: .top, color: .red, thickness: 1)
    view.layer.addBorder(edge: .bottom, color: .red, thickness: 1)
    

    注意:您可以将此函数用于 多个对象(例如uiview、uilabel、uibutton等) ,比如看这个例子

    let MyView = UIView()
    MyView.layer.addBorder(edge: .top, color: .red, thickness: 1)
    
    let MyLabel = UILabel()
    MyLabel.layer.addBorder(edge: .top, color: .red, thickness: 1)
    
    let MyButton = UIButton()
    MyButton.layer.addBorder(edge: .top, color: .red, thickness: 1)
    
    let MyImageView = UIImageView()
    MyImageView.layer.addBorder(edge: .top, color: .red, thickness: 1)