在操场上绘图和Project for Swift之间的区别

时间:2015-08-02 03:00:06

标签: swift drawing core-graphics swift-playground

我在使用swift绘制内容方面非常新,最近我获得了一个应该做我需要的代码(有一个矩形地板上有10个表格)。这段代码似乎在游乐场中完美运行(预览"眼睛"在右侧显示代码调用了我想要的图像)但是当我将它放在ViewDidLoad()下的ViewController中并运行应用程序时,没有出现。我不确定我错过了什么,因为我将确切的代码复制并粘贴到我的项目中,似乎无法正常工作。我在故事板中没有改变任何内容,我把它留作空白视图控制器。任何帮助将不胜感激。这是代码。

//: Playground - noun: a place where people can play

import UIKit

struct Table {
    let x: Int
    let y: Int
}

var tables = [
    Table(x: 2, y: 3), Table(x: 4, y: 3), Table(x: 6, y: 3),
    Table(x: 1, y: 5), Table(x: 3, y: 5), Table(x: 5, y: 5), Table(x: 7, y: 5),
    Table(x: 2, y: 7), Table(x: 4, y: 7), Table(x: 6, y: 7)]

let cafeWidth = 8
let cafeHeight = 10

let cafeView = UIView(frame: CGRect(x: 0, y: 0, width: 300, height: 200))
cafeView.backgroundColor = UIColor(white: 0.9, alpha: 1.0)

func viewForCoordinate(#x: Int, #y: Int, #size: CGSize) -> UIView {
    let centerX = Int(cafeView.frame.size.width / CGFloat(cafeWidth)) * x
    let centerY = Int(cafeView.frame.size.height / CGFloat(cafeHeight)) * y
    let view = UIView(frame: CGRect(x: 0, y: 0, width: size.width, height: size.height))
    view.center = CGPoint(x: centerX, y: centerY)
    return view
}

// draw the grid
for row in 1..<cafeHeight {
    for column in 1..<cafeWidth {
        let gridDot = viewForCoordinate(x: row, y: column, size:    CGSize(width: 1, height: 1))
        gridDot.backgroundColor = UIColor.blackColor()
        cafeView.addSubview(gridDot)
    }
}

// draw the seats
for table in tables {
    let tableView = viewForCoordinate(x: table.x, y: table.y, size: CGSize(width: 20, height: 20))
    tableView.layer.cornerRadius = 8
    tableView.backgroundColor = UIColor(hue: 100/360.0, saturation: 0.44, brightness: 0.33, alpha: 1)
    cafeView.addSubview(tableView)
}

1 个答案:

答案 0 :(得分:1)

您的&#34; cafeView&#34;永远不会添加到ViewController。 将其添加到viewDidLoad函数的底部:self.view.addSubview(cafeView)