Swift常量&变量
2018-06-25 本文已影响18人
iOS_July
前言
优先使用常量
[let]
,只有发现标识符需要修改时,再使用变量,防止在其他不希望修改的地方,不小心将值改掉
常量的本质:指向内存地址不可以修改,可以通过内存地址找到对应的对象,之后修改对象内部的属性
OC创建对象&Swift创建对象[类型()]
:
OC:UIView *view = [[UIView alloc] init];
Swift:var view : UIView = UIView()
通过内存地址找到对应的对象,之后修改对象内部的属性
let view2 : UIView = UIView()
view2.alpha = 0.5
view2.backgroundColor = UIColor.red
view2.frame = CGRect(x: 0, y: 0, width: 100, height: 100)
例子[创建一个UIView对象,并在其中添加一个UIButton,点击按钮,切换UIView对象的背景颜色]
import UIKit
fileprivate let SCREEN_WIDTH : CGFloat = UIScreen.main.bounds.width
fileprivate let SCREEN_HEIGHT : CGFloat = UIScreen.main.bounds.height
class ViewController: UIViewController {
var customView : UIView = UIView()
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
}
func setupUI() {
//创建UIView对象
let viewRect = CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT)
let view : UIView = UIView(frame: viewRect)
//设置view属性
view.backgroundColor = UIColor.purple
//将view加入到当前控制器中
self.view .addSubview(view)
customView = view
//创建UIButton对象
let btn : UIButton = UIButton()
//给btn设置属性
btn.frame = CGRect(x: 10, y: 300, width: SCREEN_WIDTH-20, height: 30)
btn.backgroundColor = UIColor.white
btn.titleLabel?.textAlignment = .center
btn .setTitleColor(UIColor.gray, for: .normal)
btn.setTitle("点我换色", for: .normal)
btn.layer.cornerRadius = 5;
btn.layer.masksToBounds = true
btn.addTarget(self, action: #selector(clickBtn), for: .touchUpInside)
//将btn加入到view中
view.addSubview(btn)
}
@objc
func clickBtn(btn : UIButton) {
btn.setTitle("再换一种", for: .normal)
customView.backgroundColor = UIColor.randomColor
}
}
extension UIColor {
//返回随机颜色
class var randomColor: UIColor {
get {
let red = CGFloat(arc4random()%256)/255.0
let green = CGFloat(arc4random()%256)/255.0
let blue = CGFloat(arc4random()%256)/255.0
return UIColor(red: red, green: green, blue: blue, alpha: 1.0)
}
}
}