加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Swift - 使用UIView给页面添加4×4方格

发布时间:2020-12-14 07:16:59 所属栏目:百科 来源:网络整理
导读:1,下面是一个利用UIView来给页面上绘制灰色方块的例子,效果图如下: 代码如下: 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 cl
1,下面是一个利用UIView来给页面上绘制灰色方块的例子,效果图如下:
代码如下:
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
46
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: "微软雅黑" numberLabel.text = "(value)"
. (pos.x,pos.y,monospace!important; min-height:inherit!important">addSubview(numberLabel)
.value = value
backgroundColor = colorMap[value]
}
required (coder aDecoder: NSCoder ) {
(coder : aDecoder)
}

使用:
51
//数字格子的宽度
= 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.
}
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读