swift - UITextField 的用法


1,文本框的創建,有如下幾個樣式:

public enum UITextBorderStyle : Int {

    case none 無邊框

    case line 直線邊框

    case bezel 圓角矩形邊框

    case roundedRect 邊線+陰影
}
let textField = UITextField(frame:CGRect(x:50,y:240,width:self.view.bounds.size.width - 100,height:50)) //設置邊框樣式為圓角矩形 textField.borderStyle = .roundedRect self.view.addSubview(textField)

2,文本框提示文字

textField.placeholder="請輸入用戶名"

3,文字大小超過文本框長度時自動縮小字號,而不是隱藏顯示省略號

textField.adjustsFontSizeToFitWidth=true  //當文字超出文本框寬度時,自動調整文字大小
textField.minimumFontSize=14  //最小可縮小的字號

4,水平/垂直對齊方式

/** 水平對齊 **/
textField.textAlignment = .right //水平右對齊
textField.textAlignment = .center //水平居中對齊
textField.textAlignment = .left //水平左對齊
textField.textAlignment = .justified 

textField.textAlignment = .natural
 
/** 垂直對齊 **/
textField.contentVerticalAlignment = .top  //垂直向上對齊
textField.contentVerticalAlignment = .center //垂直居中對齊
textField.contentVerticalAlignment = .bottom //垂直向下對齊
textField.contentVerticalAlignment = .fill  //填充滿
/*水平對其的屬性和垂直對齊是一樣的*/

5,背景圖片設置

textField.borderStyle = .none //先要去除邊框樣式
textField.background=UIImage(named:"background1");

6,清除按鈕(輸入框內右側小叉

textField.clearButtonMode=.whileEditing  //編輯時出現清除按鈕
textField.clearButtonMode=.unlessEditing  //編輯時不出現,編輯后才出現清除按鈕
textField.clearButtonMode=.always  //一直顯示清除按鈕

7,設置文本框關聯的鍵盤類型

default:系統默認的虛擬鍵盤
aSCII Capable:顯示英文字母的虛擬鍵盤
numbers and Punctuation:顯示數字和標點的虛擬鍵盤
URL:顯示便於輸入數字的虛擬鍵盤
number Pad:顯示便於輸入數字的虛擬鍵盤
phone Pad:顯示便於撥號呼叫的虛擬鍵盤
name Phone Pad:顯示便於聊天撥號的虛擬鍵盤
email Address:顯示便於輸入Email的虛擬鍵盤
decimal Pad:顯示用於輸入數字和小數點的虛擬鍵盤
twitter:顯示方便些Twitter的虛擬鍵盤
web Search:顯示便於在網頁上書寫的虛擬鍵盤
asciiCapableNumberPad  //顯示便於輸入數字的虛擬鍵盤 只支持iOS10

textField.keyboardType = .numberPad

8,使文本框在界面打開時就獲取焦點,並彈出輸入鍵盤

textField.becomeFirstResponder()

9,使文本框失去焦點,並收回鍵盤

textField.resignfirstresponder()

10,設置鍵盤return鍵的樣式

textField.returnKeyType = .done //表示完成輸入
textField.returnKeyType = .go //表示完成輸入,同時會跳到另一頁
textField.returnKeyType = .search //表示搜索
textField.returnKeyType = .join //表示注冊用戶或添加數據
textField.returnKeyType = .next //表示繼續下一步
textField.returnKeyType = .send //表示發送 textField.returnKeyType = .yahoo //雅虎 textField.returnKeyType = .done //顯示完成 textField.returnKeyType = .emergencyCall //顯示緊急呼叫

11,鍵盤return鍵的響應

//設置代理
class FirstyViewController: UIViewController,UITextFieldDelegate 

實現代理方法

func textFieldShouldReturn(textField:UITextField) -> Bool
    {
        //收起鍵盤
        textField.resignFirstResponder()
        //打印出文本框中的值
        print(textField.text)
        return true;
    }

12,點擊空白處回收鍵盤

  override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        textField.resignFirstResponder()
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM