swift - 自动填充在构建后偶尔会失败,并且无法工作(Swift)

标签 swift drawing

我已经离开游戏太久了。有人知道这里发生了什么吗?

这是 YouTube video我正在看,供引用。

Check errors here

代码如下:

import UIKit

class DrawExamples: UIView {

    override func drawRect(rect: CGRect) {
        // context is the object used for drawing
        let context = UIGraphicsGetCurrentContext()
        CGContextSetLineWidth(context, 3.0)
        CGContextSetStrokeColorWithColor(context, UIColor.purpleColor().CGColor)

        /*
        //straight line
        CGContextMoveToPoint(context, 30, 30)
        CGContextAddLineToPoint(context, 150, 320)
        */

        CGContextMoveToPoint(context, 50, 50)
        CGContextAddLineToPoint(context, 90, 130)
        CGContextAddLineToPoint(context, 180, 100)
        CGContextAddLineToPoint(context, 90, 60)
        CGContextAddLineToPoint(context, 90, 130)


        //Actually draw the path
        CGContextStrokePath(context)

    }
}

最佳答案

方法签名已更改,在 Swift 5 中您可以使用以下代码:

class DrawExamples: UIView {

    override func draw(_ rect: CGRect) {
        if let context = UIGraphicsGetCurrentContext() {
            context.setLineWidth(3.0)
            context.setStrokeColor(UIColor.purple.cgColor)

            context.move(to: CGPoint(x: 50, y: 50))
            context.addLine(to: CGPoint(x: 90, y: 130))
            context.addLine(to: CGPoint(x: 180, y: 100))
            context.addLine(to: CGPoint(x: 90, y: 60))
            context.addLine(to: CGPoint(x: 90, y: 130))
            context.strokePath()
        }
    }
}

在自定义类中配置 View 后,您可以为 Storyboard 上的 View 设置此类: enter image description here

结果你会看到:

enter image description here

关于swift - 自动填充在构建后偶尔会失败,并且无法工作(Swift),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59907741/

相关文章:

ios - 如何获取方法 "func tableView(tableView: UITableView, numberOfRowsInSection section: Int)"中的单元格?

ios - 如何在 swift 中创建自定义标签栏?

ios - 制作圆形动画的正确方法是什么?

c# - 在屏幕上画线?

c# - 如何在 .NET 中绘制 "on top"的托管控件?

ios - 更改 UINavigationBar 后退按钮的后退箭头位置

iOS:编辑 TableView 中的项目问题

drawing - 在计算机上绘制想法的应用程序

c++ - 使用DrawEllipse(GDI+)绘制手写笔画点

swift - 如何从另一个类的确切实例引用属性?