自定义view
import UIKit
class GPLView: UIView {
/*
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
// Drawing code
}
*/
//颜色映射表,不同的数字颜色不同
let colorMap = [
2:UIColor.red,
4:UIColor.orange,
8:UIColor.yellow,
16: UIColor.green,
32:UIColor.brown,
64:UIColor.blue,
128:UIColor.purple,
256:UIColor.cyan,
512:UIColor.lightGray,
1024:UIColor.magenta,
2048:UIColor.black
]
//在设置值时,更新视图的背景和文字
var value:Int = 0{
didSet{
backgroundColor = colorMap[value]
numberLabel.text="\(value)"
}
}
var numberLabel:UILabel!
//声明一个自定义初始化方法
init(pos:CGPoint, width:CGFloat, value:Int) {
numberLabel = UILabel(frame: CGRect(x: 0, y: 0, width: width, height: width))
numberLabel.textColor = UIColor.white
numberLabel.textAlignment = .center
numberLabel.minimumScaleFactor = 0.5
numberLabel.font = UIFont(name:"微软雅黑", size:20)
numberLabel.text = "\(value)"
super.init(frame:CGRect(x:pos.x , y: pos.y, width: width, height: width))
addSubview(numberLabel)
self.value = value
backgroundColor = colorMap[value]
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
import UIKit
class ViewController: UIViewController {
//游戏方格维度
var dimension:Int = 4
//数字格子的宽度
var width:CGFloat = 50
//格子与格子的间距
var padding:CGFloat = 6
//保存背景图数据
//var backgrounds:Array<GPLView>!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//self.backgrounds = Array<GPLView>()
//改成主视图背景白色背景
self.view.backgroundColor = UIColor.white
setupGameMap()
}
func setupGameMap()
{
var x:CGFloat = 50
var y:CGFloat = 150
for i in 0..<dimension
{
print(i)
y = 150
for j in 0..<dimension
{
//随机2的1~11次方
var val:Int = 2<<Int(arc4random_uniform(10))
//初始化视图
var background = GPLView(pos: CGPoint(x:x,y:y), width: self.width, value: val)
self.view.addSubview(background)
//将视图保存起来,以备后用
//backgrounds.append(background)
y += padding + width
}
x += padding+width
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
网友评论