内容来自于斯担福大学 iOS 公开课
-
项目效果
Simulator Screen Shot - iPhone SE - 2018-06-20 at 09.49.36.png
1.单个按钮的实现
1.1 按钮内容的实现
- 在View中添加一个UIButton 设置表情文字,不是图片。
- 注意:表情文字也是文字 一样可以设置大小等属性


1.2 按钮的交互
- 事件
- 选中按钮,按住
ctrl
键,同时按住鼠标左键进行拖拽连线。
- 选中按钮,按住

- 按钮的交互
-
按钮点击时设置不同的表情文字
-
Xcode中输入表情文字:
ctrl + cmd + space
-
设置表情文字的同时更改按钮的背景颜色(可以用代码,也可以直接在代码中使用颜色选项卡,Xcode8以后。)
Snip20180620_4.png
-

@IBAction func touchCard(_ sender: UIButton) {
flipCard(withEmoji: "🏄🏻♂️", on: sender)
}
/// 设置按钮的内容
func flipCard(withEmoji emoji: String, on button: UIButton) -> Void {
// 如果有表情,清空,否之设置
if button.currentTitle == emoji {
button.setTitle("", for: .normal)
button.backgroundColor = #colorLiteral(red: 0.9471735358, green: 0.5837251544, blue: 0.191911608, alpha: 1)
} else {
button.setTitle(emoji, for: .normal)
button.backgroundColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
}
}
2.两个按钮的实现
2.1 拷贝按钮
- 在storyboard中直接将第一个按钮拷贝一份
注意:在拷贝时,也会将事件一起拷贝


2.2 实现第二个按钮的交互
- 去掉拷贝中的事件连线,重新绑定新的事件。
@IBAction func touchSecondCard(_ sender: UIButton) {
flipCard(withEmoji: "🏄🏻♂️", on: sender)
}
3. 显示点击次数
3.1 增加显示标签
-
增加UIlabel
Snip20180620_8.png
/// 点击次数(属性)
@IBOutlet weak var flipCountLabel: UILabel!
- 增加一个属性来记录操作数量
var flipCount: Int = 0
- 展示内容
/// 点击按钮(事件)
@IBAction func touchCard(_ sender: UIButton) {
flipCount += 1
flipCountLabel.text = "Flips: \(flipCount)"
flipCard(withEmoji: "🍆", on: sender)
}
@IBAction func touchSecondCard(_ sender: UIButton) {
flipCount += 1
flipCountLabel.text = "Flips: \(flipCount)"
flipCard(withEmoji: "🏄🏻♂️", on: sender)
}
3.2 didSet
-
在上面的代码中,发现每次设置了计数以后,都要对显示内容进行修改。
-
使用didSet来进行设置
var flipCount: Int = 0 {
didSet {
flipCountLabel.text = "Flips: \(flipCount)"
}
}
4. 多个按钮的实现
4.1 实现集合连接
- 将第一个按钮作为属性连线到代码文件中, 此时注意方式.

@IBOutlet var cardButtons: [UIButton]!
- 将其它的按钮也连接到这个属性中



- 事件绑定

4.2 修改已连接属性名的处理
- 此时发现,
cardButons
中少写了一个t
。


4.3 获得每个按钮在集合中的位置
- 按钮在集合中的位置与连线的顺序相关
/// 点击按钮(事件)
@IBAction func touchCard(_ sender: UIButton) {
flipCount += 1
let index = cardButtons.index(of: sender) ?? 0
print(index)
}
4.4 实现多表情
- 增加一个表情包集合
/// 表情符号集合
var emojiChoices = ["🐱", "🍐", "🚐", "👻"]
- 函数实现
/// 点击按钮(事件)
@IBAction func touchCard(_ sender: UIButton) {
flipCount += 1
let index = cardButtons.index(of: sender) ?? 0
flipCard(withEmoji: emojiChoices[index], on: sender)
}
小结
- 表情文字也是文字, Xcode中输入: ctrl + cmd + space
- 连接控件属性、交互事件、集合
- 连线控件中的名称修改
- didSet的使用
- 多控件的处理
- 使用连线集合的方式(集合下标与连接顺序有关)
- 也可以将每个按钮单独连线到代码文件中
- 还可以设置每个按钮为不同的tag
网友评论