我正在尝试制作一个显示网格的iOS屏幕,其方块可以使用滑块调整大小。目前我只是使用一个按钮来测试增加平方尺寸。
我从这里攻击了一些代码: Swift / UIView / drawrect - how to get drawrect to update when required
我的问题是,虽然更新了正确的IS,但我希望每次按下按钮都能初始化它。上述链接的最终回复超出了我的微薄理解。
这是我的代码:
import UIKit
let screenSize = UIScreen.mainScreen().bounds
var screenWidth = screenSize.width
var screenHeight = screenSize.height*0.9
var squareSize: Int = 10
class ViewController: UIViewController {
// create squares and initialise it with a frame
var squares = SquaresSubclass(frame: CGRectMake(0, 0, screenWidth, screenHeight))
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(squares)
}
@IBAction func buttonPressed(sender: AnyObject) {
squareSize = squareSize + 1
squares.setNeedsDisplay()
}
}
class SquaresSubclass: UIView {
// initialise with the frame specified above
override init(frame: CGRect) {
super.init(frame: frame)
}
// no clue - copied from example
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
}
// loop CGRects across and down the screen
override func drawRect(rect: CGRect) {
var xPos = 5
let numberX = Int(0.98*screenWidth)/squareSize
var yPos = 20
let numberY = Int(0.96*screenHeight)/squareSize
for var y = 0; y<numberY ; y++ {
for var x = 0; x<numberX ; x++ {
let color:UIColor = UIColor.yellowColor()
let drect = CGRect(x: CGFloat(xPos), y: CGFloat(yPos), width: CGFloat(squareSize),height: CGFloat(squareSize))
let bpath:UIBezierPath = UIBezierPath(rect: drect)
color.set()
bpath.stroke()
xPos = xPos + squareSize
}
yPos = yPos + squareSize
xPos = 5
}
}
}
答案 0 :(得分:0)
如果您希望系统在视图上为drawRect:
致电,请在该视图上致电setNeedsDisplay()
。
答案 1 :(得分:0)
您在现有图形之上绘制更多线条。在重绘网格之前清除图形上下文:
CGContextClearRect(UIGraphicsGetCurrentContext(),self.bounds)