Draw line in UIView

后端 未结 8 832
粉色の甜心
粉色の甜心 2020-12-02 05:52

I need to draw a horizontal line in a UIView. What is the easiest way to do it. For example, I want to draw a black horizontal line at y-coord=200.

I am NOT using In

8条回答
  •  -上瘾入骨i
    2020-12-02 06:15

    Based on Guy Daher's answer.

    I try to avoid using ? because it can cause an application crash if the GetCurrentContext() returns nil.

    I would do nil check if statement:

    class CustomView: UIView 
    {    
        override func draw(_ rect: CGRect) 
        {
            super.draw(rect)
            if let context = UIGraphicsGetCurrentContext()
            {
                context.setStrokeColor(UIColor.gray.cgColor)
                context.setLineWidth(1)
                context.move(to: CGPoint(x: 0, y: bounds.height))
                context.addLine(to: CGPoint(x: bounds.width, y: bounds.height))
                context.strokePath()
            }
        }
    }
    

提交回复
热议问题