函数
函数传进去的值想在函数里面改变,加个inout
例:a: inout In
函数 封装一段代码
函数重载 :两个相同名字的函数 , 参数类型或个数不同
闭包
闭包后面+() 是执行
定义闭包
let add ={
(a:Int, b:Int) -> Int in
return a + b
}
let plus = add(1,2)//执行闭包
//1.省略参数类型
var add: (Int, Int) -> Int
add = {
(a, b) -> Int in
return a + b }
result = add(1, 2) print(result)
//2.省略返回值类型
add = {
(a, b) in
return a + b }
result = add(123, 345) print(result)
//3.省略参数列表的圆括号
add = {
a, b in
return a + b }
result = add(456, 789) print(result
//4.省略参数列表,使用位置参数
add = {
return $0 + $1 }
result = add(678, 890) print(result)
闭包里面的可执行代码只有一句,可以省略return
add={$0 + $1}
var label = UILabel()
var texfield = UITextField()
var ranNum = arc4random_uniform(100)
//定义一些viewController成员变量
//设置背景图片
let bg = UIImageView(frame: CGRectMake(0, 20, 320, 568))
bg.image = UIImage(named:"1")
self.view.addSubview(bg)
//label框
label.frame = CGRectMake(0, 20, 320, 50)
label.text = "在输入框输入一个[0,100]的数字"
label.textColor = UIColor.redColor()
//label.backgroundColor = UIColor.redColor()
label.textAlignment = .Center
self.view.addSubview(label)
//文本框
texfield.frame = CGRectMake(100, 100, 100, 50)
texfield.backgroundColor = UIColor.init(red: 1, green: 0.5, blue: 0.6, alpha: 1)
texfield.textAlignment = .Center
texfield.returnKeyType = .Done
texfield.addTarget(self, action: #selector(exit), forControlEvents: .EditingDidEndOnExit)//点击右下角的done键隐藏键盘
texfield.font = UIFont.boldSystemFontOfSize(20)//设置字体
texfield.borderStyle = .RoundedRect //文本框的边框风格
texfield.placeholder = "输入数字" //占位符显示的内容
texfield.keyboardType = .Default //键盘类型
texfield.textColor = UIColor.redColor() //输入文字的颜色
texfield.clearsOnBeginEditing = true //再次输入的时候,清除上一次输入
texfield.clearButtonMode = .WhileEditing //添加清除输入框的小按键 (内容最后的x)
self.view.addSubview(texfield)
//确定按键
let btn = UIButton(type:.Custom)
let image = UIImage(named: "ok")
btn.setImage(image, forState: .Normal)
btn.setTitle("", forState: .Normal)
btn.adjustsImageWhenHighlighted = true
btn.frame = CGRect(x:50, y:300,width: 200 ,height: 200)
self.view.addSubview(btn)
//点击执行部分
btn.addTarget(self, action: #selector(didClick), forControlEvents: .TouchUpInside)
//再猜一次按键
let gueAga = UIButton(type: .System)
gueAga.frame = CGRectMake(100, 150, 100, 100)
gueAga.setTitle("再猜一次", forState: .Normal)
self.view.addSubview(gueAga)
//点击执行部分
gueAga.addTarget(self, action: #selector(guessAgain), forControlEvents: .TouchUpInside)
//点击diClickbutton实现的功能
func didClick () {
let b = UInt32(texfield.text!)
if texfield.text == "" || b > 100 || b < 0{
label.text = "在输入框输入一个[0,100]的数字"
}else if b > ranNum{
label.text = "太大了"
print("太大了")
}else if b < ranNum{
label.text = "太小了"
print("太小了")
}else{
label.text = "猜对了"
print("猜对了")
}
}
//点击再猜一次实现的功能
func guessAgain(){
ranNum = arc4random_uniform(100)
label.text = "猜一猜"
}
//设置点击view隐藏键盘
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
self.view.endEditing(true)