Swift中TextField

 


       

         // 判斷文本框 是否爲空
        if IDTextField?.text?.isEmpty == true {
            
            JRToast.showWithText("請輸入帳號", duration: 1.5);
 
            return;
            
        }
swift

 


//
//  UITextField+Extension.swift
//  EasyHome
//
//  Created by codeIsMyGirl on 16/5/5.
//  Copyright © 2016年 codeIsMyGirl. All rights reserved.
//

import Foundation

/*
 
 這是一個最頂級的類
 
 對指定類 進行構造方法的擴展
 
 convenience 表示 遍歷構造函數

 */

import Foundation

// 對 UITextField 進行構造方法擴展

extension UITextField {
    
    /// 無佔位圖
    convenience init(stringPlaceholder: String) {
        
        self.init();
        
        // 提示默認提示符字符
        placeholder = stringPlaceholder;
        
        // 設置邊框屬性
        borderStyle = .RoundedRect;
        
        // 清除方式
        clearButtonMode = .WhileEditing;
        
        /*
         一直顯示
         Always
         
         當前焦距內 顯示
         WhileEditing
         
         從不顯示
         Never
         
         焦距 不在當前 textField 顯示
         UnlessEditing
         
         */
    }

    /// 有佔位圖
    convenience init(imageView: UIImageView, string: String, isSecure : Bool) {

        self.init();
        
        // 左側佔位圖
        leftView = imageView;
        
        // 老是顯示 imageView 的樣式
        leftViewMode = .Always;
        
        // 提示默認提示符字符
        placeholder = string;
        
        // 設置邊框屬性
        borderStyle = .RoundedRect;
        
        /*
         
         代碼建立 默認 無邊框
         
         虛線 邊框
         RoundedRect
         
         
         */

        // 打開 暗文顯示
        secureTextEntry = isSecure;
        
        // 清除方式
        clearButtonMode = .WhileEditing;
    }
}
less

限定文本框輸入長度

// 添加事件
        <#textField#>.addTarget(self, action: "inputTextFiledTolengthChange:", forControlEvents: .EditingChanged);

    /// 上一次的次數
    private var countString = "0";

    // MARK:
    // MARK: 輸入了文本框
    /// 輸入了文本框
    @objc private func inputTextFiledTolengthChange(sender: UITextField) {
 
        if sender.text!.characters.count >= 5 {
            
            sender.text = countString;
            
            return;
        }
        
        countString = sender.text ?? "0";
 
    }

參考:http://www.jianshu.com/p/0ba0395f4060
相關文章
相關標籤/搜索