【问题标题】:Difference between drawing in playground and Project for Swift在 Playground 中绘图和 Project for Swift 之间的区别
【发布时间】:2015-08-02 03:00:05
【问题描述】:

我在使用 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)
}

【问题讨论】:

    标签: swift drawing core-graphics swift-playground


    【解决方案1】:

    您的“cafeView”永远不会添加到 ViewController。 将此添加到 viewDidLoad 函数的底部:self.view.addSubview(cafeView)

    【讨论】:

      猜你喜欢
      • 2017-07-17
      • 2015-07-21
      • 2016-11-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-11
      • 2016-06-27
      • 1970-01-01
      相关资源
      最近更新 更多