1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | import UIKit class VIEwController : UIVIEwController { //游戏方格维度 var dimension: Int = 4 //数字格子的宽度 wIDth: CGfloat = 50 //格子与格子的间距 padding: = 6 //保存背景图数据 backgrounds: Array < UIVIEw >! overrIDe func vIEwDIDLoad() { super .vIEwDIDLoad() self .backgrounds = >() //改成主视图背景白色背景 .vIEw.backgroundcolor = UIcolor .whitecolor() setupGameMap() } setupGameMap() { x: = 50 y: = 150 for i in 0..<dimension { println (i) y = 150 j 0..<dimension { //初始化视图 background = (frame: CGRectMake (x,y,wIDth,wIDth)) background.backgroundcolor = .darkGraycolor() .vIEw.addSubvIEw(background) //将视图保存起来,以备后用 backgrounds.append(background) y += padding + wIDth } x += padding+wIDth } } dIDReceiveMemoryWarning() { .dIDReceiveMemoryWarning() // dispose of any resources that can be recreated. } } |
2,进阶版 - 继承UIVIEw实现自定义方块组件(有颜色和数字) 方块组件:TileVIEw.swift
TileVIEw { //颜色映射表,不同的数字颜色不同 let colorMap = [ 2: .redcolor(), 4: .orangecolor(), 8: .yellowcolor(), 16: .greencolor(), 32: .browncolor(), 64: .bluecolor(), 128: .purplecolor(), 256: .cyancolor(), 512: .lightGraycolor(), 1024: .magentacolor(), 2048: .blackcolor() ] //在设置值时,更新视图的背景和文字 value: = 0{ dIDSet { backgroundcolor = colorMap[value] numberLabel.text= "\(value)" } } numberLabel: UILabel ! //初始化视图 init (pos: CGPoint ,wIDth: ) { numberLabel = (0,wIDth)) numberLabel.textcolor = .whitecolor() numberLabel.textAlignment = NSTextAlignment . Center numberLabel.minimumScaleFactor = 0.5 numberLabel.Font = UIFont (name: "微软雅黑" "\(value)" . (pos.x,pos.y,monospace!important; min-height:inherit!important">addSubvIEw(numberLabel) .value = value backgroundcolor = colorMap[value] } required (coder aDecoder: NSCoder ) { (coder : aDecoder) } |
使用:
//数字格子的宽度 = 50 //格子与格子的间距 = 6 //保存背景图数据 >! vIEwDIDLoad() { .vIEwDIDLoad() >() //改成主视图背景白色背景 .whitecolor() setupGameMap() } setupGameMap() { = 50 = 150 0..<dimension { (i) y = 150 0..<dimension { //随机2的1~11次方 val: = 2<< (arc4random_uniform(10)) (x:x,y:y),wIDth: .wIDth,value: val) .vIEw.addSubvIEw(background) //将视图保存起来,以备后用 backgrounds.append(background) y += padding + wIDth } x += padding+wIDth } dIDReceiveMemoryWarning() { .dIDReceiveMemoryWarning() // dispose of any resources that can be recreated. } } |
以上是内存溢出为你收集整理的Swift - 使用UIView给页面添加4×4方格全部内容,希望文章能够帮你解决Swift - 使用UIView给页面添加4×4方格所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)