UITextField的一些笔记

2016-08-25  本文已影响0人  老韩在简书

暴走萝莉

ViewController.swift

import UIKit



//MARK: - 生命周期和属性
class ViewController: UIViewController {
    
    //属性:
    let player = YTPersonImageView()
    
    
    //生命周期:
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //创建界面
        self.creatUI()
        
        //创建定时器
        NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: "timerAction", userInfo: nil, repeats: true)
    }
    
    //定时器
    func timerAction() {
        
        self.player.move()
    }
    
    
}

//MARK: - 搭界面
extension ViewController{
    
    func creatUI(){
        
        //1.背景图
        let bgImageView = UIImageView.init(frame: self.view.bounds)
        let path = NSBundle.mainBundle().pathForResource("map.png", ofType: nil)
        bgImageView.image = UIImage.init(contentsOfFile: path!)
        self.view.addSubview(bgImageView)
        
        
        
        //3.小人
        self.player.frame = CGRectMake(0, 0, 64, 64)
        self.player.center = self.view.center
        self.player.image = UIImage.init(named: "player_down_1.png")
        self.player.animationDuration = 0.5
        self.view.addSubview(self.player)
        
        
        //2.方向按钮
        //左
        let leftBtn = UIButton.init(frame: CGRectMake(72, 503, 80, 80))
        leftBtn.setImage(UIImage.init(named: "button_left"), forState: .Normal)
        leftBtn.addTarget(self, action: "touchDownAction:", forControlEvents: .TouchDown)
        leftBtn.addTarget(self, action: "touchUpAction:", forControlEvents: .TouchUpInside)
        leftBtn.tag = YTDirection.Left.rawValue
        self.view.addSubview(leftBtn)
        //右
        let rightBtn = UIButton.init(frame: CGRectMake(232, 503, 80, 80))
        rightBtn.setImage(UIImage.init(named: "button_right"), forState: .Normal)
        rightBtn.addTarget(self, action: "touchDownAction:", forControlEvents: .TouchDown)
        rightBtn.addTarget(self, action: "touchUpAction:", forControlEvents: .TouchUpInside)
        rightBtn.tag = YTDirection.Right.rawValue
        self.view.addSubview(rightBtn)
        
        //上
        let upBtn = UIButton.init(frame: CGRectMake(152, 444, 80, 80))
        upBtn.setImage(UIImage.init(named: "button_up"), forState: .Normal)
        upBtn.addTarget(self, action: "touchDownAction:", forControlEvents: .TouchDown)
        upBtn.addTarget(self, action: "touchUpAction:", forControlEvents: .TouchUpInside)
        upBtn.tag = YTDirection.Up.rawValue
        self.view.addSubview(upBtn)
        
        //下
        let downBtn = UIButton.init(frame: CGRectMake(152, 543, 80, 80))
        downBtn.setImage(UIImage.init(named: "button_down"), forState: .Normal)
        downBtn.addTarget(self, action: "touchDownAction:", forControlEvents: .TouchDown)
        downBtn.addTarget(self, action: "touchUpAction:", forControlEvents: .TouchUpInside)
        downBtn.tag = YTDirection.Down.rawValue
        self.view.addSubview(downBtn)
        
        
        
    }
    
}

//MARK: - 按钮点击
extension ViewController{
    //按钮弹起
    func touchUpAction(btn:UIButton){
        
        //不能再移动
        self.player.isMoving = false
    }
    
    //按钮按下
    func touchDownAction(btn:UIButton) {
        
        //1.告诉小人的移动方向
        switch btn.tag {
        case YTDirection.Up.rawValue:
            self.player.moveDirection = .Up
        case YTDirection.Down.rawValue:
            self.player.moveDirection = .Down
        case YTDirection.Right.rawValue:
            self.player.moveDirection = .Right
        case YTDirection.Left.rawValue:
            self.player.moveDirection = .Left
            
        default:
            print("不存在的方向")
        }
        
        //2.可以移动
        self.player.isMoving = true
        
        
    }
}


YTPersonImageView.swift

import UIKit


//MARK: - 方向枚举
enum YTDirection:Int{
    
    case Left 
    case Right
    case Up
    case Down
}

//MARK: - 全局变量
let screenH = UIScreen.mainScreen().bounds.size.height
let screenW = UIScreen.mainScreen().bounds.size.width


class YTPersonImageView: UIImageView {
    
    //属性:
    //1.移动方向
    var moveDirection: YTDirection = .Down
    //2.是否移动
    var isMoving = false{
        
        //在给isMoving赋值的时候,会自动调用这个didSet代码块
        didSet{
            
            //如果是变成移动状态
            if isMoving == true {
                
                //设置当前方向对应的动画数组
                switch self.moveDirection {
                case .Left:
                    self.animationImages = self.leftArray
                case .Right:
                    self.animationImages = self.rightArray
                case .Up:
                    self.animationImages = self.upArray
                default:
                    self.animationImages = self.downArray
                    
                }
                
                self.startAnimating()
                
            }else{
                
                //如果是变成停止状态
                self.stopAnimating()
                self.image = self.animationImages![0]
                
            }
            
            
        }
    }
    
    
    
    
    
    
    //3.动画数组
    //懒加载,就是当前这个变量只创建一次,并且是在使用的时候才会创建,不使用就不会创建
    //左
    lazy var leftArray:[UIImage] = {
        var array = [UIImage]()
        for item in 1...3{
            
            let image = UIImage.init(named: "player_left_\(item)")
            array.append(image!)
        }
        return array
    }()
    //右
    lazy var rightArray:[UIImage] = {
        var array = [UIImage]()
        for item in 1...3{
            
            let image = UIImage.init(named: "player_right_\(item)")
            array.append(image!)
        }
        return array
    }()
    //上
    lazy var upArray:[UIImage] = {
        var array = [UIImage]()
        for item in 1...3{
            
            let image = UIImage.init(named: "player_up_\(item)")
            array.append(image!)
        }
        return array
    }()
    //下
    lazy var downArray:[UIImage] = {
        var array = [UIImage]()
        for item in 1...3{
            
            let image = UIImage.init(named: "player_down_\(item)")
            array.append(image!)
        }
        return array
    }()
    
    
    //方法:
    //小人移动
    func move() {
        
        //判断小人儿是否可以动
        if isMoving == false {
            return
        }
        //如果可以移动
        switch self.moveDirection {
            
        case .Down:
            
            if self.frame.origin.y + 1 >= screenH - self.frame.size.height {
                
                return
            }
            self.frame.origin.y += 1
            
            
        case .Up:
            
            if self.frame.origin.y - 1 <= 0 {
                
                return
            }
            
            self.frame.origin.y -= 1
            
        case .Left:
            
            if self.frame.origin.x - 1 <= 0 {
                return
            }
            
            self.frame.origin.x -= 1
            
        default:
            
            if self.frame.origin.x + 1 >= screenW - self.frame.size.width {
                
                return
            }
            
            self.frame.origin.x += 1
            
        }
    }
}
屏幕快照 2016-08-25 下午8.23.38.png

2.自定义键盘

ViewController.swift

import UIKit

class ViewController: UIViewController,YTKeyBoardDelegate {
    
    //MARK: - 属性
    var textField = UITextField()
    
    //MARK: - 生命周期
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //1.创建一个UITextField对象
        textField = UITextField.init(frame: CGRectMake(100, 100, 200, 50))
        textField.backgroundColor = UIColor.init(red: 230/255.0, green: 230/255.0, blue: 230/255.0, alpha: 230/255.0)
        self.view.addSubview(textField)
        
        //使用自己的键盘
        let keyBoard = YTKeyBoard(frame: CGRectMake(0,0,100,256))
        keyBoard.frame = CGRectMake(0, 0, 100, 250)
        
        //设置代理
        keyBoard.delegate = self
        
        keyBoard.backgroundColor = UIColor.init(red: 105/255.0, green: 105.0/255.0, blue: 105/255.0, alpha: 105/255.0)
        textField.inputView = keyBoard
        
    }
    
    //MARK: - YTKeyBoard delegate
    func showContent(button: UIButton) {
        
        if button.currentTitle == "返回" {
            
            //收起键盘
            self.textField.resignFirstResponder()
            
            return
        }
        
        if button.currentTitle == "C" {
            
            //判断textField中的文字是否为空,不为空才做删除操作
            if self.textField.text?.characters.count > 0 {
                //拿到最后一个字符的index
                let last  = self.textField.text!.endIndex.predecessor()
                
                //移除最后一个字符
                var text = self.textField.text!
                text.removeAtIndex(last)
                
                self.textField.text = text
                
            }
            
            return
        }
        
        
        textField.text = textField.text! + button.currentTitle!
    }
    
    
}

YTKeyBoard.swift

import UIKit

//MARK: - YTKeyBoard协议
protocol YTKeyBoardDelegate{
    
    //让代理去显示指定的按钮上的内容
    func showContent(button:UIButton)
}


//1.在创建当前类的对象的时候,去创建在这个视图上所有的子视图,并且添加(不需要设置子视图的frame)
//2.计算子视图的frame

//MARK: - 构造方法和属性
class YTKeyBoard: UIView {
    
    //代理
    var delegate: YTKeyBoardDelegate? = nil
    
    
    //重写父类的构造方法
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        //在这个方法中去创建所有的子视图
        self.creatSubViews()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
}

//MARK: - 创建子视图
extension YTKeyBoard{
    
    //计算子视图的frame
    //1.这个方法第一次调用是在当前视图将要显示在界面上的时候才会调用(在这个方法中拿到的当前视图的frame是视图最终frame值)
    //当当前视图显示出来之后,如果视图frame发生改变,就会自动调用这个方法
    override func layoutSubviews() {
        super.layoutSubviews()
        
        //间距
        let margin:CGFloat = 10
        //宽度
        let keyW = self.frame.size.width
        //高度
        let keyH = self.frame.size.height
        //列数
        let col: CGFloat = 3
        //按键的宽度
        let btnW = (keyW - (col+1)*margin) / col
        //行数
        let line: CGFloat = 4
        //按键的高度
        let btnH = (keyH - (line+1)*margin) / line
        
        
        //        Y:margin+(btnH+margin)*(i/col)
        //        X:margin+(btnW+margin)*(i%col)
        //1.拿到当前视图上的子视图
        var i = 0
        for item in self.subviews {
            
            //a.计算按键的frame
            //找到按键对应的按钮
            if item.tag == 100 {
                
                let btnX = margin + (btnW+margin) * CGFloat(i%Int(col))
                let btnY = margin + (btnH+margin) * CGFloat(i/Int(col))
                item.frame = CGRectMake(btnX, btnY, btnW, btnH)
                
                //找到一个按钮i加1
                i += 1
            }
            
            //b.计算imageView的frame
            if item.tag == 200 {
                
                item.frame = CGRectMake(20, -40, 50, 50)
            }
        }
        
        
        
        
        
    }
    
    
    
    //创建子视图
    func creatSubViews() {
        //1.键盘上显示的内容
        let titles = ["1","2","3","4","5","6","7","8","9","C","0","返回"]
        
        //2.遍历数组,创建对应的按钮
        //i ->下标
        //item -> 数组元素
        for (_,item) in titles.enumerate() {
            
            //创建对应的按钮
            let btn = UIButton.init()
            btn.setTitle(item, forState: .Normal)
            btn.backgroundColor = UIColor.init(red: 230/255.0, green: 230/255.0, blue: 230/255.0, alpha: 230/255.0)
            // 键盘上的字体颜色
            btn.setTitleColor(UIColor.blackColor(), forState: .Normal)
            btn.tag = 100
            btn.addTarget(self, action: "btnAction:", forControlEvents: .TouchDown)
            self.addSubview(btn)
        }
        
        //3.创建一个imageView
        let imageView = UIImageView.init()
        imageView.image = UIImage.init(named: "luffy1")
        self.addSubview(imageView)
        imageView.tag = 200
        
    }
    
    
    //按钮点击
    func btnAction(btn:UIButton){
        
        //YTKeyBoard想要将按钮上的内容显示到ViewController中的textField上。但是YTKeyBoard是做不到,但是ViewController可以。
        //确定三要素:
        //委托:YTKeyBoard
        //协议:将指定按键上的内容显示在textField上
        //代理:ViewController
        
        
        //currentTitle属性->按钮上的文字
        print(btn.currentTitle)
        
        //让代理去显示按钮上的内容
        self.delegate?.showContent(btn)
        
    }
    
    
}

屏幕快照 2016-08-25 下午8.25.21.png

3.UITextField基础知识

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        //  UITextField:UIControl:UIView
        // ============UIView的属性和方法=============
        // 1. 创建UITextField对象
        let textField = UITextField.init(frame: CGRectMake(100, 100, 200, 50))
        // 2. 添加到界面上
        self.view.addSubview(textField)
        // 3. 设置背景颜色
        textField.backgroundColor = UIColor.yellowColor()
        
        // 4. 再创建一个UITextField对象
        let textField1 = UITextField.init(frame: CGRectMake(100, 200, 200, 50))
        self.view.addSubview(textField1)
        textField1.backgroundColor = UIColor.yellowColor()
        textField1.delegate = self
        
        // ==========textField的专有属性和方法==========
        
        // (1). 文字相关
        // 1. text属性
        // 设置文本输入框的内容
        textField.text = ""
        // 拿到文本输入框的内容
        print(textField.text)
        
        // 2. 文字颜色
        textField.textColor = UIColor.brownColor()
        
        // 3. 设置文字字体
        textField.font = UIFont.systemFontOfSize(14)
        
        // 4. 设置占位文字(在输入框的内容为空的时候就会显示出来)
        textField.placeholder = "请输入账号"
        
        // 5. 设置文本的对齐方式(默认:左对齐)
        textField.textAlignment = .Left
        
        // 6. 密文显示(默认是false)
        textField.secureTextEntry = true
        
        
        //(2) 显示相关
        // 1. 设置文本框的样式
        textField.borderStyle = .RoundedRect
        // 2. 设置清除按钮模式
        // Always -> 一直显示
        // Never -> 从不显示(默认)
        // WhileEditing ->  当文本框输入处于编辑状态的时候显示
        // UnlessEditing ->  当文本框输入处于非编辑状态的时候显示
        // 注: 当文本输入框中有光标的时候就是处于编辑状态
        textField.clearButtonMode = .Always
        
        // 3. 左视图
        let leftImageView = UIImageView.init(frame: CGRectMake(0, 0, 50, 50))
        leftImageView.image = UIImage.init(named: "luffy4")
        // 设置做视图
        textField.leftView = leftImageView
        //设置做视图的显示模式(确定什么时候显示,默认是从不显示)
        textField.leftViewMode = .Always
        
        // 4. 右视图
        // 当又视图显示的时候,清除按钮不能显示
        /*
        let rightLabel = UILabel.init(frame: CGRectMake(0, 0, 40, 40))
        rightLabel.text = "你好"
        textField.rightView = rightLabel
        textField.rightViewMode = .Always
        */
        
        // (3) 键盘相关
        // 1. 设置键盘上返回按钮的样式
        textField.returnKeyType = .Done
        
        // 2. 键盘样式
        textField.keyboardType = .Default
        
        // 3.设置自定义的键盘
        // 自定义的键盘,只有高度有效。宽度是屏幕的宽度
        let myInputView = UIView.init(frame: CGRectMake(0, 0, 0, 256))
        myInputView.backgroundColor = UIColor.redColor()
//        textField.inputView = myInputView
        
        // 4. 设置子键盘
        let accessoryView = UIView.init(frame: CGRectMake(0, 0, 0, 50))
        accessoryView.backgroundColor = UIColor.greenColor()
        textField.inputAccessoryView = accessoryView
        
        // (4) 设置代理
        // textField -> 委托
        // self -> 代理
        textField.delegate = self
        
        
        
    }


}

extension ViewController:UITextFieldDelegate {
    
    // 6. 当按键盘上的返回按钮的时候,会自动调用
    func textFieldShouldReturn(textField: UITextField) -> Bool {
        
        print("返回按钮被点击")
        
        // 收起键盘
        // 1. 放弃第一响应者
        textField.resignFirstResponder()
        // 2. 直接让指定的textField结束编辑
        textField.endEditing(true)
        // 3. 让self.view上的所有的子视图都结束编辑
        self.view.endEditing(true)
        
        
        return true
        
    }
    
    // 5. 当点击textField弹出来的键盘上的按键的时候会自动调用这个方法
    // 参数1: 委托
    // 参数2: 当前输入的的字符所在的位置
    // 参数3: 当前输入的字符串(在键盘上按的键的值)
    // 返回值: 是否可以改变textField的text属性(); false -> 按键盘上的按键无效
    func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
        
        print(range)
        print(string)
        if string == "0" {
            print("进入秘密页")
        }
        
        return true
        
    }
    
    // 4. 当文本输入框已经结束编辑的时候会自动调用这个方法
    func textFieldDidEndEditing(textField: UITextField) {
        
        print("已经结束编辑")
        
    }
    
    
    // 2. 当文本输入框已经开始编辑的时候会自动调用这个方法
    func textFieldDidBeginEditing(textField: UITextField) {
        
        print("已经开始编辑")
        
    }
    
    
    // 3.当文本输入框将要结束编辑的时候会自动调用这个方法
    // 返回: 设置当前的textField是否可以结束编辑()默认是true
    func textFieldShouldEndEditing(textField: UITextField) -> Bool {
        
        print("将要结束编辑")
        
        // 要求文本输入框的文字长度要大于等于8的时候才能结束编辑
        if textField.text?.characters.count >= 8 {
            return true
        }
        
        
        return false
        
    }
    
    
    
    
    
    // 1. 在textField将要开始编辑的时候会自动调用
    // 参数:当前这个协议对应的的委托
    // 返回值:设置当前的textField是否可以进行编辑(默认是true)
    func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
        
        print("将要开始编辑")
        return true  // false -> 让textField不能进行编辑
    }
}

上一篇下一篇

猜你喜欢

热点阅读