swift第二周实训心得

2016年11月27日 星期日 早

这周集宁还是比较冷的,刚下完一场雪,不过一天天的又回温了,感觉今年真的很不错啊😏,整个人每天心情美美哒。

不过时间过的好快啊,转眼第二周又结束了。当然实训又学到不少东西😄。下面再来总结一下,不过还是那句话,希望不要喷。

day05

UI控件

UILabel UITextField UIImageView UIButton

  • UILabel
override func viewDidLoad() {
        super.viewDidLoad()
//创建label
  let label = UILabel()
  label.frame = CGRect(x: 100, y: 100, width: 200, height: 100)
  self.view.addSubview(label)
  //给label设置文字
  label.text = "hello, zhangsan"
  //文字的颜色
  label.textColor = #colorLiteral(red: 0.5568627715, green: 0.3529411852, blue: 0.9686274529, alpha: 1)
  //文字的字体及字号
  label.font = UIFont.systemFont(ofSize: 18)
  //label文本对齐方式
  label.textAlignment = .center
  //label背景颜色
  label.backgroundColor = UIColor.orange
  //文字的换行模式如果是0的话,不限制
  label.numberOfLines = 1
  //如果label大小不足以放下文字,省略模式
  label.lineBreakMode = .byTruncatingTail

  • 运行结果:
  • UITextField
override func viewDidLoad() {
        super.viewDidLoad()
//textField
  let textfield = UITextField()
  textfield.frame = CGRect(x: 100, y: 250, width: 200, height: 40)
  view.addSubview(textfield)
  //设置placehold
  textfield.placeholder = "请输入密码:"
  //设置边框样式
  //textfield.borderStyle = UITextBorderStyle.roundedRect
  textfield.borderStyle = .none
  //文字清除样式
  //textfield.clearsOnBeginEditing = true
  //边框样式
  //textfield.background = UIImage(named: "3f.jpg")
        
  let inset = UIEdgeInsets(top: 19, left: 30, bottom: 19, right: 18)
  textfield.background = UIImage(named: "k.jpg")?.resizableImage(withCapInsets: inset, resizingMode: UIImageResizingMode.stretch)
        
  //编辑时出来删除按钮(小❎)
  textfield.clearButtonMode = .whileEditing
  //左边视图的样式(小🔑)
  //textfield.leftView = UIImageView(image: UIImage(named: "ys.jpg"))
  //什么时候显示左边视图
  textfield.leftViewMode = .always
        
  //代理方法
  textfield.delegate = self;
        
  //设置密码样式(密文㊙️)
  textfield.isSecureTextEntry = true
        
  self.usertextfield = textfield
    }
    
//textfieldDelegate方法
  //是否可以开始编辑
  func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
       //return false
       return true   //false不可编辑
  }
    
  //开始编辑
  func textFieldDidBeginEditing(_ textField: UITextField) {
       print("开始编辑")
  }
    
  //结束编辑
  func textFieldDidEndEditing(_ textField: UITextField) {
       print("结束编辑")
  }
    
  //是否可以结束编辑
  func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
       return true
  }
    
  //return键
  func textFieldShouldReturn(_ textField: UITextField) -> Bool {
       textField.resignFirstResponder()
       return true
  }
    
  //是否可以被清除
  func textFieldShouldClear(_ textField: UITextField) -> Bool {
       return true
  }
    
  override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
       //取消第一响应者
       self.usertextfield.resignFirstResponder()
       //当光标在textfield之上的时候  FirstResponder()
       //如果想让textfield处于编辑状态   becomeFirstResponder()
       //想让键盘回收的时候  resignFirstResponder()
  }

//图片拉伸
//extension UIImage {
        
//}
  • 运行结果:
  • 练习
override func viewDidLoad() {
        super.viewDidLoad()
  view.backgroundColor = #colorLiteral(red: 0.4745098054, green: 0.8392156959, blue: 0.9764705896, alpha: 1)
        
//用户名
  let username = UITextField()
  username.frame = CGRect(x: 90, y: 250, width: 200, height: 40)
  view.addSubview(username)
  //设置placehold
  username.placeholder = "请输入用户名:"
  //设置字体大小
  username.font = UIFont.systemFont(ofSize:14)
  //设置边框样式
  username.borderStyle = UITextBorderStyle.roundedRect
  //文字清除样式
  username.clearsOnBeginEditing = true
  //编辑时出来小❎
  username.clearButtonMode = .whileEditing
  //左视图样式(小🎭)
  username.leftView = UIImageView(image: UIImage(named: "xr.png"))
  //什么时候显示左边视图
  username.leftViewMode = .always
        
//密码
  let password = UITextField()
  password.frame = CGRect(x: 90, y: 290, width: 200, height: 40)
  view.addSubview(password)
  //设置placehold
  password.placeholder = "请输入密码:"
  //设置字体大小
  password.font = UIFont.systemFont(ofSize:14)
  //设置边框样式
  password.borderStyle = .roundedRect
  //文字清除样式
  password.clearsOnBeginEditing = true
  //编辑时出来小❎
  password.clearButtonMode = .whileEditing
  //左视图样式(小🔑)
  password.leftView = UIImageView(image: UIImage(named: "ys.jpg"))
  //什么时候显示左边视图
  password.leftViewMode = .always
  //设置密码样式(密文㊙️)
  password.isSecureTextEntry = true
        
  }
 
//开始编辑
  func textFieldDidBeginEditing(_ textField: UITextField) {
      print("开始编辑")
  }
  • 运行结果:
  • UIImageView
override func viewDidLoad() {
        super.viewDidLoad()
//UIImageView
  let imageview = UIImageView()
  imageview.frame = CGRect(x: 0, y: 100, width: 440, height: 280)
  self.view.addSubview(imageview)
  //1⃣️通过名字来加载
  //imageview.image = UIImage(named:"nv.jpg")
  //2⃣️根据路径来加载
  //从main boudle来获取
  //let path = Bundle.main.path(forResource: "nv", ofType: ".jpg")
  //let image = UIImage(contentsOfFile: path!)
  //imageview.image = image
        
  //名字加载图片:图片内容加载到内存,下次加载不需要再去资源包中读取图片,节省时间
  //路径加载图片:不会把图片加载到内容,下次加载需要再去资源包中读取,节省空间
        
  var arr : [UIImage] = [UIImage]()
  for index in 1...5 {
      //构造图片的名字
      let imageName = "\(index).jpg"
      //根据名字初始化图片对象
      let image = UIImage(named: imageName)
      //动态绑定
      if let _ = image {  
         arr.append(image!)
      }
  }
  imageview.animationImages = arr
  //设置动画执行时间为1秒
  imageview.animationDuration = 3
  //设置动画执行次数(不重复)
  imageview.animationRepeatCount = 0
  //开始动画
  imageview.startAnimating() 
}

  • 运行结果:
  • UIButton
override func viewDidLoad() {
        super.viewDidLoad()
//Button
  //初始化button
  let button = UIButton(type: .system)
  button.frame = CGRect(x: 10, y: 100, width: 100, height: 40)
  self.view.addSubview(button)
  //button的样式
  //给button添加文字
  button.setTitle("注册", for: .normal)  //被选中为高亮状态
  //设置文字颜色
  button.setTitleColor(UIColor.red, for: .normal)
  //设置图片
  button.setImage(UIImage(named:"bj.png")?.withRenderingMode(.alwaysOriginal), for: .normal)  //withRenderingMode修改图片原始状态
        
  //给button添加点击事件
  //1 方法执行对象
  //2 执行的方法
  //3 触发方式
  button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside )  //枚举类型:点语法
  //设置背景颜色
  button.backgroundColor = UIColor.yellow
    }
    
  //点击方法
  func buttonAction() {
       print("点击了button")
    }
    
   //API初始化方法
   override func didReceiveMemoryWarning() {
       super.didReceiveMemoryWarning()
       // Dispose of any resources that can be recreated.
   }
  • 运行结果:
  • command+n新建一个Cocoa Touch Class,名为:MyVeiw.swift,键入:
//内部私有,外部不需要了解也无法更改
    private var label : UILabel!
    private var textfield : UITextField!
    //给label赋值
    var title : String {
        //重写set、get方法
        set {
            self.label.text = newValue
        }
        get {
            if let _ = self.label.text {
                return self.label.text!
            }
            return ""
        }
    }
    //只能存不能取
    var placehold : String {  //文本框输入内容
        set {
            self.textfield.placeholder = newValue
        }
        get {
            return ""
        }
    }
    //只能取不能存
    var textfieldContent : String {  //获取内容
        get {
            if let _ = self.textfield.text {  //可选绑定
            return self.textfield.text!
            } else {
                return ""
            }
        }
    }
    
    var labelframe : CGRect {
        set {
          self.label.frame = newValue
        }
        get {
            return self.label.frame
        }
    }
    
    var textfieldFrame : CGRect {
        set {
            self.textfield.frame = newValue
        }
        get {
            return self.textfield.frame
        }
    }
    
    //重写父类的init
    override init(frame: CGRect) {
        super.init(frame: frame)
        //通过属性重写值
        self.label = UILabel(frame: CGRect(x: 10, y: 10, width: self.frame.size.width / 3, height: self.frame.size.height - 20))
        self.textfield = UITextField(frame: CGRect(x: self.label.frame.maxX + 5, y: 10, width: self.frame.size.width / 3, height: self.frame.size.height - 20))
        self.addSubview(self.label)
        self.addSubview(self.textfield)
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
  • 在ViewController.swift中super.viewDidLoad()下键入如下代码,将ViewController改为自己新建的MyViewController;
  let subview = MyView(frame: CGRect(x: 100, y: 100, width: 200, height: 40))
  subview.title = "用户名"
  subview.placehold = "请输入密码"
  self.view.addSubview(subview)

  • 运行结果:

day06

视图控制器

  • 为什么要有视图控制器
  • 若有xib文件,加载,否则不加载;
//初始化
    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
        //1 加载的xib文件
        //2 bundle
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
  • 视图控制器的生命周期
    init loadView、viewDidLoad、viewWillAppear、viewDidAppear、viewWillDisappear、viewDidDisappear
  • 生命周期每个方法干什么用的(一些实际的应用场景)
//加载view(只走一次)
    override func loadView() {
        super.loadView()   //进行根视图操作
        //替换当前控制器的view
        //let imageview = UIImageView(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height))
        //self.view = imageview
    }

//加载相关资源(只走一次)
    override func viewDidLoad() {
        super.viewDidLoad()  //进行逻辑操作
        //视图控制器
        let button = UIButton(type: .system)
        button.frame = CGRect(x: 100, y: 100, width: 50, height: 40)
        //响应事件
        button.addTarget(self, action: #selector(buttonAction(button:)), for: .touchUpInside)
        button.setTitle("返回", for: .normal)
        self.view.addSubview(button)
    }
    
//视图将要显示在屏幕上(走很多次)
   override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    }
    
//显示在屏幕上
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
    }
    
//视图将要从屏幕消失
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
    }
    
//视图已经消失
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
    }
  • 模拟推出
    • 在ViewController.swift中添加方法:
//响应方法
    func buttonAction(button: UIButton) {
        // 模态推出下一个界面,一般用于注册
        let viewcontroller = SecondViewController()
        //1 要推出下一个控制器
        //2 是否有动画
        //3 推出完成之后毁掉
        self.present(viewcontroller, animated: true) {
            
        }
    }
  • 模态推出之后一定要dismiss
    • 在SecondViewController.swift中添加:
     //响应方法
     func buttonAction(button: UIButton) {
         //当页面回收回去
         self.dismiss(animated: true, completion: nil)
     }
  • view是lazy属性的

  • 属性传值

//属性传值
    var seconderviewcontroller : SecondViewController!

UIControl的子类

UISlider UISwitch UISegmentedControl

  • UISlider
override func viewDidLoad() {
        super.viewDidLoad()
//UISlider滑杆
        //slider高度没用
        let slider = UISlider(frame: CGRect(x: 100, y: 50, width: 200, height: 40))
        self.view.addSubview(slider)
        //如果滑杆没有设置最小最大值,默认0-1
        
        //给滑杆添加事件
        slider.addTarget(self, action: #selector(sliderAction(slider:)), for: . valueChanged)
        //设置滑杆的最大值
        slider.maximumValue = 100
        //设置滑杆的最小值
        slider.minimumValue = 0
        //设置最小值的颜色
        //slider.minimumTrackTintColor = UIColor.gray
        //设置最大值的颜色
        //slider.maximumTrackTintColor = UIColor.black
        //设置滑块的颜色
        //slider.thumbTintColor = UIColor.brown
        //自定义滑杆的图片
        let sliderimage = UIImage(named: "bj.jpg")
        let thumbimage = UIImage(named: "btn.jpg")
        let smallimage = UIImage(named: "xiao")
        let bigimage = UIImage(named: "da")
        //设置音量的两张图片
        slider.maximumValueImage = bigimage
        slider.minimumValueImage = smallimage
        //设置滑杆滑过去区域的图片
        slider.setMinimumTrackImage(sliderimage, for: .normal)
        //设置未滑过的图片
        slider.setMaximumTrackImage(sliderimage, for: .highlighted)
        //拖动滑杆时thumb会处于高亮状态
        slider.setThumbImage(thumbimage, for: .normal)
        //松开滑杆时thumb会处于正常状态
        slider.setThumbImage(thumbimage, for: .highlighted) 
    }
    
//滑杆事件
    func sliderAction(slider: UISlider) {
        print(slider.value) //value当前的值
    }
  • 运行结果:
  • UISwitch
override func viewDidLoad() {
        super.viewDidLoad()
//UISwitch开关
        let sw = UISwitch()
        sw.center = CGPoint(x: 100, y: 100)
        self.view.addSubview(sw)
        //TargetAction模式
        sw.addTarget(self, action: #selector(swAction(sw:)), for: .valueChanged)
        //打开的颜色
        sw.onTintColor = UIColor.orange
        //本身的颜色
        sw.tintColor = UIColor.cyan
        //滑块的颜色
        sw.thumbTintColor = UIColor.gray
    }
    
//开关的事件
    func swAction(sw: UISwitch) {
        print(sw.isOn)
    }
  • 运行结果:
  • UISegmentedControl
override func viewDidLoad() {
        super.viewDidLoad()
//UIControl的子类
        //UISegmentedControl
        let arr = ["张三","李四","赵六"]
        let seg : UISegmentedControl = UISegmentedControl(items: arr)
        seg.center = CGPoint(x: 100, y: 100)
        self.view.addSubview(seg)
        //seg:局部变量生命周期长
        //
        //
        seg.addTarget(self, action: #selector(segAction(seg:)), for: .valueChanged)
        //默认第0个选中
        seg.selectedSegmentIndex = 0
        //点击之后是否属于选中状态(true:否)
        //seg.isMomentary = true
        //修改item内容的偏移量
        //let size = CGSize(width: -10, height: -10)
        //seg.setContentOffset(size, forSegmentAt: 0)
    }
    
//UISegmentedControl事件
    func segAction(seg: UISegmentedControl) {
        //选中第几个
        print(seg.selectedSegmentIndex)
        //设置第几个文字
        //seg.setTitle("\(seg.selectedSegmentIndex)", forSegmentAt: seg.selectedSegmentIndex)
    }
  • 运行结果:

手势

UITapGestureRecognizer、UILongPressGestureRecognizer、UISwipeGestureRecognizer、UIRotationGestureRecognizer、UIPinchGestureRecognizer、UIPinchGestureRecognizer

  • UITapGestureRecognizer
override func viewDidLoad() {
        super.viewDidLoad()
//轻拍
        let tap = UITapGestureRecognizer()
        //添加到view上
        self.view.addGestureRecognizer(tap)
        tap.addTarget(self, action: #selector(tapAction))
        //几个手指轻拍
        tap.numberOfTouchesRequired = 2
        //拍几下
        tap.numberOfTapsRequired = 2
}

//UITapGestureRecognizer轻拍方法
    func tapAction() {
        print("轻拍")
    }
  • UILongPressGestureRecognizer
override func viewDidLoad() {
        super.viewDidLoad()
//长按
        let long = UILongPressGestureRecognizer()
        //添加到view上
        self.view.addGestureRecognizer(long)
        long.addTarget(self, action: #selector(longAction))
        //最小长按时间(默认0.5)
        long.minimumPressDuration = 1
        //长按时可以挪动的最小距离(默认10)
        long.allowableMovement = 15
        //长按的手指数数量和次数同轻拍
}

//UILongPressGestureRecognizer长按方法
    func longAction() {
        print("长按")
    }

  • UISwipeGestureRecognizer
- override func viewDidLoad() {
        super.viewDidLoad()
//清扫
        let swipe = UISwipeGestureRecognizer()
        swipe.direction = .left
        self.view.addGestureRecognizer(swipe)
        swipe.addTarget(self, action: #selector(swipeAction(swipe:)))
        
        let swipe1 = UISwipeGestureRecognizer()
        swipe.direction = .right
        self.view.addGestureRecognizer(swipe1)
        swipe1.addTarget(self, action: #selector(swipeAction(swipe:)))
}

//UISwipeGestureRecognizer清扫方法
    //传参:往哪个方向扫
    func swipeAction(swipe: UISwipeGestureRecognizer) {
        //获取清扫方向
        let dir = swipe.direction
        //print("向左清扫")
        //print("清扫的方向:\(dir)")
        if dir == .left {
            
        } else if dir == .right {
            
        }
    }
  • UIRotationGestureRecognizer
override func viewDidLoad() {
        super.viewDidLoad()
        //旋转
        let rotation = UIRotationGestureRecognizer()
        self.view.addGestureRecognizer(rotation)
        rotation.addTarget(self, action: #selector(rotationAction))
        //旋转角度
        //rotation.rotation
}

//UIRotationGestureRecognizer旋转方法
    func rotationAction() {
        print("旋转")
    }

  • UIPinchGestureRecognizer
override func viewDidLoad() {
        super.viewDidLoad()
        //捏合
        let pinch = UIPinchGestureRecognizer()
        self.view.addGestureRecognizer(pinch)
        pinch.addTarget(self, action: #selector(pinchAction))
        //缩放
        //pinch.scale
        */

}

//UIPinchGestureRecognizer捏合方法
    func pinchAction() {
        print("捏合")
    }

  • UIPanGestureRecognizer
override func viewDidLoad() {
        super.viewDidLoad()
//拖动
        let pan = UIPanGestureRecognizer()
        pan.addTarget(self, action: #selector(panAction(pan:)))
        self.view.addGestureRecognizer(pan)
        //缩放
        //pan.scale
        //拖动坐标 pan.translation
}

//UIPinchGestureRecognizer拖动方法
    func panAction(pan:UIPanGestureRecognizer) {
        //返回当前拖动的位置在self.view上的位置
         print(pan.translation(in: self.view))
    }

day07

UIScrollView

  • UIScrollView创建和常用属性
override func viewDidLoad() {
        super.viewDidLoad()
//UIScrollView的创建和常用属性
        let scrollview = UIScrollView(frame: CGRect(x: 0, y: 0, width: 380, height: 220))
        self.view.addSubview(scrollview)
        //设置颜色
        scrollview.backgroundColor = UIColor.cyan
        //设置内容区域的大小
        scrollview.contentSize = CGSize(width: 380, height: 220)
        //是否整页翻动
        scrollview.isPagingEnabled = true
        //触壁反弹(不反弹)
        scrollview.bounces = false
        //展示滑动条(无)
        //水平
        scrollview.showsHorizontalScrollIndicator = true
        //滑条的颜色
        scrollview.indicatorStyle = .white
        //竖直
        //scrollview.showsVerticalScrollIndicator
        //是否关闭任何拖拽
        //scrollview.isScrollEnabled = false
        //添加图片
        self.loadImage(scrollview: scrollview)
        //设置代理
        scrollview.delegate = self
    }
    
    //scrollViewDelegate方法
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        //print("任何偏移都会执行")
        //获取偏移量
        //print(scrollView.contentOffset)
    }
    
    //开始拖拽
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        print("开始拖拽")
    }
    
    //结束拖拽
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        print("结束拖拽")
    }
    
    //减速
    func scrollViewWillBeginDecelerating(_ scrollView: UIScrollView) {
        print("开始减速")
    }
    
    //结束减速
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        print("结束减速")
    }
    
    //加载图片
    func loadImage(scrollview: UIScrollView) {
        let imageview = UIImageView(frame: CGRect(x: 0, y: 0, width: 380, height: 220))
        imageview.image = UIImage(named: "lyf.jpeg")
        scrollview.addSubview(imageview)
        let imageview1 = UIImageView(frame: CGRect(x: 380, y: 0, width: 380, height: 220))
        imageview1.image = UIImage(named: "lyf1.jpeg")
        scrollview.addSubview(imageview1)
        let imageview2 = UIImageView(frame: CGRect(x: 760, y: 0, width: 380, height: 220))
        imageview2.image = UIImage(named: "lyf2.jpeg")
        scrollview.addSubview(imageview2)
        let imageview3 = UIImageView(frame: CGRect(x: 1140, y: 0, width: 380, height: 220))
        imageview3.image = UIImage(named: "lyf3.jpeg")
        scrollview.addSubview(imageview3)
    }
  • 运行结果:
  • 练习
override func viewDidLoad() {
        super.viewDidLoad()
//UIScrollView的创建和常用属性
        let scrollview = UIScrollView(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height))
        self.view.addSubview(scrollview)
        //设置颜色
        scrollview.backgroundColor = UIColor.cyan
        //设置内容区域的大小
        scrollview.contentSize = CGSize(width: self.view.frame.size.width * 4, height: self.view.frame.size.height)
        //🌿设置偏移量
        //scrollview.contentOffset = CGPoint(x: self.view.frame.size.width, y: 0)
        //🌿是否整页翻动
        scrollview.isPagingEnabled = true
        //🌿触壁反弹(不反弹)
        scrollview.bounces = false
        //展示滑动条(无)
        //水平
        scrollview.showsHorizontalScrollIndicator = true
        //🌿滑条的颜色
        scrollview.indicatorStyle = .white
        //竖直
        //scrollview.showsVerticalScrollIndicator
        //是否关闭任何拖拽
        //scrollview.isScrollEnabled = false
        //添加图片
        self.loadImage(scrollview: scrollview)
        //设置代理
        scrollview.delegate = self
        //放大/缩小
        scrollview.minimumZoomScale = 0.2
        scrollview.maximumZoomScale = 2
    }
    
    //缩放要实现的方法(返回要缩放的控件)
    func viewForZooming(in scrollView: UIScrollView) -> UIView? {
        for view in scrollView.subviews {
            //类型判断
            //判断子视图是什么类型
            if view is UIImageView {
                return view
            }
        }
        return nil
    }
    
    //scrollViewDelegate方法
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        //print("任何偏移都会执行")
        //🌿获取偏移量
        //print(scrollView.contentOffset)
    }
    
    //开始拖拽
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        print("开始拖拽")
    }
    
    //结束拖拽
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        print("结束拖拽")
    }
    
    //减速
    func scrollViewWillBeginDecelerating(_ scrollView: UIScrollView) {
        print("开始减速")
    }
    
    //结束减速
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        print("结束减速")
    }
    
    //加载图片
    func loadImage(scrollview: UIScrollView) {
        let imageview = UIImageView(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height))
        imageview.image = UIImage(named: "1.jpg")
        scrollview.addSubview(imageview)
        let imageview1 = UIImageView(frame: CGRect(x: self.view.frame.size.width, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height))
        imageview1.image = UIImage(named: "2.jpg")
        scrollview.addSubview(imageview1)
        let imageview2 = UIImageView(frame: CGRect(x: self.view.frame.size.width * 2, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height))
        imageview2.image = UIImage(named: "3.jpg")
        scrollview.addSubview(imageview2)
        let imageview3 = UIImageView(frame: CGRect(x: self.view.frame.size.width * 3, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height))
        imageview3.image = UIImage(named: "4.jpg")
        scrollview.addSubview(imageview3)
    }

  • 运行结果:

UIPageControl、Timer

  • UIPageControl
//定义全局变量
var timer : Timer!
override func viewDidLoad() {
        super.viewDidLoad()
        //UIPageControl图片下的小点
        let page = UIPageControl()
        //一共有多少页
        page.numberOfPages = 5
        //当前多少页
        page.currentPage = 2
        //选中滑块的颜色
        page.currentPageIndicatorTintColor = UIColor.black
        //未选中滑块的颜色
        page.pageIndicatorTintColor = UIColor.gray
        //设置大小
        page.frame = CGRect(x: 100, y: 100, width: 100, height: 30)
        //设置frame的center
        page.center = CGPoint(x: 100, y: 100)
        //添加事件
        page.addTarget(self, action: #selector(pageAction(page:)), for: .valueChanged)
        self.view.addSubview(page)
        
        //UIProgressView
        //UITextView
        //UISearchBar
        //UIAlertController

//定时器关闭
    func pageAction(page: UIPageControl) {
        //当前第几个小点点被选中
        //print(page.currentPage)
        timer.invalidate()
        timer = nil
    }

  • 运行结果:
  • Timer
  • 定义全局变量(见上UIPageControl中),与UIPageControl一样放到super.viewDidLoad():
//Timer定时器
        //1 间隔时间
        //2 方法的执行对象
        //3 执行的方法
        //4 配置信息, 类似备注
        //5 true 循环执行  false 执行一次
        /*
        let timer = Timer(timeInterval: 1, target: self, selector: #selector(timerAction), userInfo: nil, repeats: true)
        //添加到主循环
        //初始化的timer
        //添加到某个模式中
        RunLoop.current.add(timer, forMode: .defaultRunLoopMode)
        //开启计时器
        timer.fire()
        */
        
        timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(timerAction), userInfo: nil, repeats: true)
        
        timer.fire()
    }

    //
    func timerAction() {
        print("1")
    }
    

轮播图片

  • 定义全局变量
var scrollerview : UIScrollView! = nil
    var pageC : UIPageControl! = nil
    var timer : Timer! = nil

  • 轮播图片
    • 定义UIScrollView和Timer
    • 添加方法
override func viewDidLoad() {
        super.viewDidLoad()
        //轮播图
        let scr = UIScrollView(frame: CGRect(x: 0, y: 100, width: self.view.frame.size.width, height: 250))
        scr.contentSize = CGSize(width: self.view.frame.size.width * 5, height: 250)
        scrollerview = scr
        //代理
        scrollerview.delegate = self
        self.view.addSubview(scr)
        for index in 1...5 {
            let name = "\(index).jpg"
            let image = UIImage(named: name)
            let x = CGFloat(index - 1) * self.view.frame.size.width
            let imageview = UIImageView(frame: CGRect(x: x, y: 0, width: self.view.frame.size.width, height: 250.0))
            imageview.image = image
            scr.addSubview(imageview)
        }
        //是否整页翻页
        scr.isPagingEnabled = true
        //触壁反弹
        scr.bounces = false
        //添加UIPageContorl
        let page = UIPageControl(frame: CGRect(x: 100, y: 320, width: self.view.frame.size.width - 200, height: 30))
        self.pageC = page
        //一共有多少页
        page.numberOfPages = 4
        //
        page.currentPage = 0
        page.addTarget(self, action: #selector(pageAction(page:)), for: .valueChanged)
        self.view.addSubview(page)
        
        //Timer
        self.timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(timerAction), userInfo: nil, repeats: true)
        //开启计时器
        timer.fire()
    }
    
//添加方法
   //开始拖拽
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        //关闭
        self.timer.invalidate()
        self.timer = nil
    }
    
    //结束拖拽
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        self.timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(timerAction), userInfo: nil, repeats: true)
        //一秒之后再执行
        let time = DispatchTime.now() + 1.0
        DispatchQueue.main.asyncAfter(deadline: time) {
            if let _ = self.timer {
            self.timer.fire()
            }
        }
    }
    
    //timer方法
    func timerAction() {
        //获取当前的偏移量offset
        let offset = self.scrollerview.contentOffset
        let width = self.view.frame.size.width
        //offset.x + width
        //让scrollerview进行滑动
        scrollerview.setContentOffset(CGPoint(x:offset.x + width, y:offset.y), animated: true)
        //if 到第四个了,跳到第一个
        if scrollerview.contentOffset.x >= width * 4 {
            let point = CGPoint(x: 0, y: 0)
            scrollerview.contentOffset = point
        }
    }
    
    //滑动执行的方法
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        //获取偏移量
        let x = scrollerview.contentOffset.x
        //根据偏移量定位到第几个点
        let width = self.view.frame.size.width
        if (x >= width * 4) {
            self.pageC.currentPage = 0
        } else {
            self.pageC.currentPage = Int(x / width)
        }
        //self.pageC.currentPage = Int(x / width) //同下
        /*
        switch x {
        case 0:
            self.pageC.currentPage = 0
        case 1 * width:
            self.pageC.currentPage = 1
        case 2 * width:
            self.pageC.currentPage = 2
        case 3 * width:
            self.pageC.currentPage = 3
        default:
            print("other")
            
        }
        */
    }
    
    //事件
    func pageAction(page: UIPageControl) {
        let index = page.currentPage
        let point = CGPoint(x: CGFloat(index) * self.view.frame.size.width, y:0)
        self.scrollerview.setContentOffset(point,animated: true)
    }
  • 运行结果:

day08

注册界面

  • 在ViewController.swift中键入:
override func viewDidLoad() {
        super.viewDidLoad()
        //注册界面
        //用户名
        view.backgroundColor = #colorLiteral(red: 0.9098039269, green: 0.4784313738, blue: 0.6431372762, alpha: 1)
        
        let userlabel = UILabel(frame: CGRect(x: 30, y: 250, width: 50, height: 40))
        view.addSubview(userlabel)
        //设置文本
        userlabel.text = "用户名"
        //设置字体大小
        userlabel.font = UIFont.systemFont(ofSize: 14)
        //设置字体颜色
        userlabel.textColor = UIColor.black
        //设置文本对齐方式
        userlabel.textAlignment = .right
        
        //密码
        let passlabel = UILabel(frame: CGRect(x: 30, y: 290, width: 50, height: 40))
        view.addSubview(passlabel)
        //设置文本
        passlabel.text = "密码"
        //设置字体大小
        passlabel.font = UIFont.systemFont(ofSize: 14)
        //设置字体颜色
        passlabel.textColor = UIColor.black
        //设置文本对齐方式
        passlabel.textAlignment = .right
        
        //用户名
        let username = UITextField()
        username.frame = CGRect(x: 90, y: 250, width: 200, height: 40)
        //设置placeholder
        username.placeholder = "请输入用户名"
        //设置字体大小
        username.font = UIFont.systemFont(ofSize: 14)
        //设置边框样式
        username.borderStyle = .roundedRect
        //编辑时出来小叉号(❎)
        username.clearsOnBeginEditing = true
        //左视图样式
        username.leftView = UIImageView(image: UIImage(named: "xr"))
        //左视图什么时候显示
        username.leftViewMode = .always
        view.addSubview(username)
        
        //密码
        let password = UITextField()
        password.frame = CGRect(x: 90, y: 290, width: 200, height: 40)
        //设置placeholder
        password.placeholder = "请输入密码"
        //设置字体大小
        password.font = UIFont.systemFont(ofSize: 14)
        //设置边框样式
        password.borderStyle = .roundedRect
        //编辑时出来小叉号(❎)
        password.clearsOnBeginEditing = true
        //左视图样式
        password.leftView = UIImageView(image: UIImage(named: "ys.jpg"))
        //左视图什么时候显示
        password.leftViewMode = .always
        //设置密码样式(密文㊙️)
        password.isSecureTextEntry = true
        view.addSubview(password)
        
        //登录
        let entry = UIButton(type:.system)
        entry.frame = CGRect(x: 110, y: 350, width: 50, height: 40)
        //添加文字
        entry.setTitle("登录", for: .normal)
        //设置文字颜色
        entry.setTitleColor(UIColor.black, for: .normal)
        //设置背景颜色
        entry.backgroundColor = UIColor.cyan
        //添加事件
        entry.addTarget(self, action: #selector(entryAction), for: .touchUpInside)
        self.view.addSubview(entry)
        
        //注册
        let register = UIButton(type: .system)
        register.frame = CGRect(x: 210, y: 350, width: 50, height: 40)
        //添加文字
        register.setTitle("注册", for: .normal)
        //设置文字颜色
        register.setTitleColor(UIColor.black, for: .normal)
        //设置背景颜色
        register.backgroundColor = UIColor.cyan
        //添加事件
        register.addTarget(self, action: #selector(registerAction), for: .touchUpInside)
        self.view.addSubview(register)
    }

    //加载view(只走一次)
    override func loadView() {
        super.loadView()   //进行根视图操作
    }
    
    //entry方法
    func entryAction() {
        // 模态推出下一个界面,一般用于注册
        let viewcontroller = SecondViewController()
        //1 要推出下一个控制器
        //2 是否有动画
        //3 推出完成之后毁掉
        self.present(viewcontroller, animated: true) {
            
        }

    }
    
    //register方法
    func registerAction() {
        // 模态推出下一个界面,一般用于注册
        let viewcontroller = ThirdViewController()
        //1 要推出下一个控制器
        //2 是否有动画
        //3 推出完成之后毁掉
        self.present(viewcontroller, animated: true) {
            
        }

    }
  • command+n新建一个Cocoa Touch Class名为SecondViewController.swift,在其中键入:
//加载view(只走一次)
    override func loadView() {
        super.loadView()
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        let label = UILabel()
        label.frame = CGRect(x: 100, y: 100, width: 200, height: 40)
        label.text = "恭喜你,登录成功!"
        self.view.addSubview(label)
        
        //视图控制器
        let button = UIButton(type: .system)
        button.frame = CGRect(x: 120, y: 250, width: 100, height: 40)
        //响应事件
        button.addTarget(self, action: #selector(buttonAction(button:)), for: .touchUpInside)
        button.setTitle("返回上一页", for: .normal)
        self.view.addSubview(button)
        
        self.view.backgroundColor = UIColor.orange

    }

    //响应方法
    func buttonAction(button: UIButton) {
        //当页面回收回去
        self.dismiss(animated: true, completion: nil)
    }
  • command+n新建一个Cocoa Touch Class名为ThirdViewController.swift,在其中键入:
//加载view(只走一次)
    override func loadView() {
        super.loadView()
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        let label = UILabel()
        label.frame = CGRect(x: 100, y: 100, width: 200, height: 40)
        label.text = "恭喜你,注册成功!"
        self.view.addSubview(label)
        
        //视图控制器
        let button = UIButton(type: .system)
        button.frame = CGRect(x: 120, y: 250, width: 100, height: 40)
        //响应事件
        button.addTarget(self, action: #selector(buttonAction(button:)), for: .touchUpInside)
        button.setTitle("返回上一页", for: .normal)
        self.view.addSubview(button)
        
        self.view.backgroundColor = UIColor.yellow
    }

    //响应方法
    func buttonAction(button: UIButton) {
        //当页面回收回去
        self.dismiss(animated: true, completion: nil)
    }
  • 运行结果:

(注:只是实现了界面布局,每个控件并没有真正实现其功能。)

改变颜色的三个滑杆,三个滑杆代表红绿蓝,修改view的颜色

    override func viewDidLoad() {
        super.viewDidLoad()
        //改变颜色的三个滑杆,三个滑杆代表红绿蓝,修改view的颜色
        //滑杆1
        let slider1 = UISlider(frame: CGRect(x: 100, y: 200, width: 200, height: 40))
        self.view.addSubview(slider1)
        //设置滑杆的最大值
        slider1.maximumValue = 100
        //设置滑杆的最小值
        slider1.minimumValue = 0
        //设置最小值的颜色
        slider1.minimumTrackTintColor = UIColor.clear
        //设置最大值的颜色
        slider1.maximumTrackTintColor = UIColor.red
        //添加事件
        slider1.addTarget(self, action: #selector(sliderAction(slider:)), for: .valueChanged)
        //slider1.thumbTintColor = UIColor.red
        
        //滑杆2
        let slider2 = UISlider(frame: CGRect(x: 100, y: 250, width: 200, height: 40))
        self.view.addSubview(slider2)
        //设置滑杆的最大值
        slider2.maximumValue = 100
        //设置滑杆的最小值
        slider2.minimumValue = 0
        //设置最小值的颜色
        slider2.minimumTrackTintColor = UIColor.clear
        //设置最大值的颜色
        slider2.maximumTrackTintColor = UIColor.green
        //添加事件
        slider2.addTarget(self, action: #selector(sliderAction(slider:)), for: .valueChanged)
        //slider2.thumbTintColor = UIColor.green
        
        //滑杆3
        let slider3 = UISlider(frame: CGRect(x: 100, y: 300, width: 200, height: 40))
        self.view.addSubview(slider3)
        //设置滑杆的最大值
        slider3.maximumValue = 100
        //设置滑杆的最小值
        slider3.minimumValue = 0
        //设置最小值的颜色
        slider3.minimumTrackTintColor = UIColor.clear
        //设置最大值的颜色
        slider3.maximumTrackTintColor = UIColor.blue
        //添加事件
        slider3.addTarget(self, action: #selector(sliderAction(slider:)), for: .valueChanged)
        //slider3.thumbTintColor = UIColor.blue
    }

    //添加方法
    func sliderAction(slider: UISlider) {
        print(slider.value) //value当前的值
        self.view.backgroundColor = UIColor(red: CGFloat(slider.value) / 255.0, green: CGFloat(slider.value) / 255.0, blue: CGFloat(slider.value) / 255.0, alpha: 1)
 
}
  • 运行结果:

一个Book类,Book中有书名和书的内容两个手势切换

  • 在ViewController.swift中新建一个Book类:
//Book类
class Book: NSObject {
    var titleName : String?
    var content : String?
    init(titleName : String, content : String) {
        self.titleName = titleName
        self.content = content
    }
}

  • 在ViewController中定义全局变量:
//书的数组
    var bookArr = [Book]()
    var titlelabel : UILabel! = nil
    var contentlabel : UILabel! = nil
    var index : Int = 0  //显示第0本书

  • 在viewDidLoad下进行手势切换:
override func viewDidLoad() {
        super.viewDidLoad()
        
        for index in 1...5 {
            let book = Book(titleName: "第\(index)篇文章", content: "第\(index)篇文章的内容")
            self.bookArr.append(book)
        }
        //手势
        let swipe = UISwipeGestureRecognizer()
        swipe.direction = .left
        self.view.addGestureRecognizer(swipe)
        swipe.addTarget(self, action: #selector(swipeAction(swipe:)))
        
        //手势
        let swipe1 = UISwipeGestureRecognizer()
        swipe1.direction = .right
        self.view.addGestureRecognizer(swipe1)
        swipe1.addTarget(self, action: #selector(swipeAction(swipe:)))
        //添加label
        self.titlelabel = UILabel(frame: CGRect(x: 100, y: 100, width: 100, height: 40))
        self.view.addSubview(titlelabel)
        
        self.contentlabel = UILabel(frame: CGRect(x: 100, y: 200, width: 300, height: 40))
        self.view.addSubview(contentlabel)
        
        //加载内容
        //先取出第0本书
        let currentBook = bookArr[index]
        self.titlelabel.text = currentBook.titleName
        self.contentlabel.text = currentBook.content
    }
    
    //方法
    func swipeAction(swipe: UISwipeGestureRecognizer) {
        
        //判断方向
        if swipe.direction == .right {
            index-=1
            if index < 0 {
                index = bookArr.count - 1
            }
        } else if swipe.direction == .left {
            index+=1
            if index >= bookArr.count {
                  index = 0
        }
    }
        
        let currentBook = bookArr[index]
        self.titlelabel.text = currentBook.titleName
        self.contentlabel.text = currentBook.content

        
    }
  • 运行结果:

day09

导航栏 navigationController

  • 两种方法进行创建item(第一种已注释):
override func viewDidLoad() {
        super.viewDidLoad()
        
        //UINavigationController
        self.view.backgroundColor = #colorLiteral(red: 0.9607843161, green: 0.7058823705, blue: 0.200000003, alpha: 1)
        //设置标题
        self.title = "消息"
        
        //创建左右视图(item)
        //左item
        //1 标题
        //2 样式
        //3 点击方法触发的对象
        //4 要执行的方法
        
        //位置没法更改
        //let leftItem1 = UIBarButtonItem(title: "左视图", style: .plain, target: self, action: #selector(leftItemAction(sender:)))
        //self.navigationItem.leftBarButtonItem = leftItem1
        //右item
        /*
        let rightItem = UIBarButtonItem(title: "右视图", style: .plain, target: self, action: #selector(leftItemAction(sender:)))
        self.navigationItem.rightBarButtonItem = rightItem
        */
        
        //根据button创建item
        let button = UIButton(type: .system)
        button.frame = CGRect(x: 0, y: 0, width: 50, height: 30)
        button.addTarget(self, action: #selector(leftItemAction(sender:)), for: .touchUpInside)
        button.setTitle("左按钮", for: .normal)
        let leftItem = UIBarButtonItem(customView: button)
        self.navigationItem.leftBarButtonItem = leftItem
        
        //self.navigationItem.leftBarButtonItems = [leftItem,leftItem1]
        
        //let arr = ["🍎","🍐"]
        //分段控制器
        //let seg = UISegmentedControl(items:arr)
        //self.navigationItem.titleView = seg
        
        //UINavigationBar
        
        let rightItem = UIButton(type: .system)
        rightItem.frame = CGRect(x: 300, y: 10, width: 50, height: 30)
        rightItem.setTitle("右按钮", for: .normal)
        rightItem.addTarget(self, action: #selector(leftItemAction(sender:)), for: .touchUpInside)
        self.navigationController?.navigationBar.addSubview(rightItem)
        //修改navigationBar的颜色(等同下)
        self.navigationController?.navigationBar.backgroundColor = UIColor.cyan
        //设置导航透明或不透明(ios6及前不透明,7后透明)
        //self.navigationController?.navigationBar.isTranslucent = true
        
        //self.navigationController?.navigationBar.barTintColor = UIColor.cyan   //不透明
        //修改bar上视图的颜色
        //self.navigationController?.navigationBar.tintColor = UIColor.red
        
        //修改title的属性 富文本
        let dic : [String : Any] = [NSFontAttributeName: UIFont.systemFont(ofSize:18),NSForegroundColorAttributeName: UIColor.brown]
        
        self.navigationController?.navigationBar.titleTextAttributes = dic
        
        //图片
        let image = UIImage(named: "44")
        self.navigationController?.navigationBar.setBackgroundImage(image, for: .default)
    }

    //方法
    func leftItemAction(sender: UIBarButtonItem) {
        
    }
  • 运行结果:

页面跳转

  • 在viewController中进行第一个页面的设置(可以跳转至第二个界面):
override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = #colorLiteral(red: 0.4745098054, green: 0.8392156959, blue: 0.9764705896, alpha: 1)
        //页面跳转
        self.title = "第一个控制器"
        let button = UIButton(type: .system)
        button.frame = CGRect(x: 300, y: 100, width: 50, height: 30)
        button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
        button.setTitle("下一页", for: .normal)
        self.view.addSubview(button)
        
    }

    //方法
    func buttonAction() {
        let second = SecondViewController()
        //推出下一个界面
        self.navigationController?.pushViewController(second, animated: true)
    }
  • command+n新建Cocoa Touch Class文件,名为SecondViewController.swift,在其中进行第二个页面的设置(可以跳转至第三界面):
 override func viewDidLoad() {
        self.view.backgroundColor = #colorLiteral(red: 0.721568644, green: 0.8862745166, blue: 0.5921568871, alpha: 1)
        super.viewDidLoad()
        self.title = "第二个控制器"
        let button = UIButton(type: .system)
        button.frame = CGRect(x: 300, y: 100, width: 50, height: 30)
        button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
        button.setTitle("下一页", for: .normal)
        self.view.addSubview(button)
   
    }

    func buttonAction() {
        //接收一下
        //let _ = self.navigationController?.popViewController(animated: true)
        let third = ThirdViewController()
        self.navigationController?.pushViewController(third, animated: true)
    }
  • command+n新建Cocoa Touch Class文件,名为ThirdViewController.swift,在其中进行第三个页面的设置(可以跳转至指定界面):
override func viewDidLoad() {
        self.view.backgroundColor = #colorLiteral(red: 0.9568627477, green: 0.6588235497, blue: 0.5450980663, alpha: 1)
        super.viewDidLoad()
        let button = UIButton(type: .system)
        button.frame = CGRect(x: 20, y: 100, width: 100, height: 30)
        button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
        button.setTitle("返回第一页", for: .normal)
        self.view.addSubview(button)

    }

    func buttonAction() {
        //回到指定控制器
        //let _ = self.navigationController?.popToViewController((self.navigationController?.topViewController)!,animated: true)
        //获取栈中所有控制器
        let arr = self.navigationController?.viewControllers
        for item in arr! {
            if item is ViewController   {
                //回到第一页
                let _ = self.navigationController?.popToViewController(item, animated: true)
            } /*else if item is SecondViewController {
                let _ = self.navigationController?.popToViewController(item, animated: true)
            }*/
        }
        //回到第一页
        let _ = self.navigationController?.popToRootViewController(animated: true)
    }

  • 运行结果:

利用闭包进行页面跳转

  • 在ViewController中进行第一个第一个界面的设置:
var content = 1
   
    override func viewDidLoad() {
        self.view.backgroundColor = #colorLiteral(red: 0.9411764741, green: 0.4980392158, blue: 0.3529411852, alpha: 1)
        
        super.viewDidLoad()
        let button = UIButton(type: .system)
        button.setTitle("下一页", for: .normal)
        button.frame = CGRect(x: 300, y: 100, width: 50, height: 40)
        button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
        self.view.addSubview(button)
        
    }
    
    //button方法
    func buttonAction() {
        let second = secondViewController()
        //把当前页面的值传递后下一个界面
        second.index = content
        self.navigationController?.pushViewController(second, animated: true)
        
    }
  • command+n新建Cocoa Touch Class文件,名为secondViewController.swift,在其中进行第二个页面的设置(可以跳转至第三界面):
//定义一个全局变量
var index : Int? = nil
    override func viewDidLoad() {
        self.view.backgroundColor = #colorLiteral(red: 0.4745098054, green: 0.8392156959, blue: 0.9764705896, alpha: 1)
        super.viewDidLoad()
        print(index!)
        
    }
  • 运行结果:

利用协议进行页面跳转

  • command+n新建Cocoa Touch Class文件,名为BViewController.swift,定义一个协议:
protocol ViewControllerDelegate {
    func sendMsg(msg: String)
}
  • 定义代理对象:
//定义代理对象
    var delegate : ViewControllerDelegate? = nil
  • 传值
override func viewDidLoad() {
        view.backgroundColor = #colorLiteral(red: 0.721568644, green: 0.8862745166, blue: 0.5921568871, alpha: 1)
        super.viewDidLoad()
        //
        self.delegate?.sendMsg(msg: "要传过去的值")
        
    }
  • ViewController遵守ViewControllerDelegate协议:
class ViewController: UIViewController,ViewControllerDelegate {
    
    override func viewDidLoad() {
        view.backgroundColor = #colorLiteral(red: 0.8039215803, green: 0.8039215803, blue: 0.8039215803, alpha: 1)
        super.viewDidLoad()
        let button = UIButton(type: .system)
        button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
        self.view.addSubview(button)
        button.setTitle("下一页", for: .normal)
        button.frame = CGRect(x: 280, y: 100, width: 100, height: 40)
    }
    
    //
    func buttonAction() {
        let b = BViewController()
        b.delegate = self
        self.navigationController?.pushViewController(b, animated: true)
    }
    func sendMsg(msg: String) {
        //接收值
        
    }
  • 运行结果:

(注:写作日期与发表日期不同步。)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 211,561评论 6 492
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,218评论 3 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 157,162评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,470评论 1 283
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,550评论 6 385
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,806评论 1 290
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,951评论 3 407
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,712评论 0 266
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,166评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,510评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,643评论 1 340
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,306评论 4 330
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,930评论 3 313
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,745评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,983评论 1 266
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,351评论 2 360
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,509评论 2 348

推荐阅读更多精彩内容