ViewController.swift部分:
// ViewController.swift
import UIKit
class ViewController: UIViewController , UITextFieldDelegate, UITextViewDelegate {
var label: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let screen = UIScreen.main.bounds
//label代碼實現(xiàn)
let labelWidth: CGFloat = 90
let labelHeight: CGFloat = 20
let labelTopView:CGFloat = 150
// let labelFrame = CGRect(x: (screen.size.width - labelWidth)/2 , y:labelTopView, width: labelWidth, height: labelHeight)
let labelFrame = CGRect(x: 0 , y:labelTopView, width: labelWidth, height: labelHeight)
self.label = UILabel(frame: labelFrame)
label.text = "Label"
label.textAlignment = NSTextAlignment.center //字體左右居中
self.view.addSubview(label)
//button代碼實現(xiàn)
let buttonWidth: CGFloat = 60
let buttonheight: CGFloat = 20
let buttonTopView: CGFloat = 240
let button = UIButton(type: UIButton.ButtonType.system)
button.setTitle("OK", for: UIControl.State.normal)
button.frame = CGRect(x: (screen.size.width - buttonWidth)/2, y: buttonTopView, width: buttonWidth, height: buttonheight)
//addTarget,第一個參數(shù)是事件處理者,第二個參數(shù)是選擇器類型,它指向事件處理方法,第三個參數(shù)是事件.
button.addTarget(self, action: #selector(onClick(_:)), for: UIControl.Event.touchUpInside)
self.view.addSubview(button)
//textfield和textview在模擬器要彈出軟鍵盤,需要先在模擬器菜單“Hardware”---“keyboard”---“Connect Hardware Keyboard”,去掉勾選.
//textfield代碼實現(xiàn)
let textFieldWidth: CGFloat = 223
let textFieldHeight: CGFloat = 30
let textFieldTopView: CGFloat = 150
let textFieldFrame = CGRect(x: (screen.size.width - textFieldWidth)/2, y: textFieldTopView, width: textFieldWidth, height: textFieldHeight)
let textField = UITextField(frame: textFieldFrame)
textField.borderStyle = UITextField.BorderStyle.roundedRect
textField.returnKeyType = UIReturnKeyType.next //設置鍵盤return鍵
textField.keyboardType = UIKeyboardType.numbersAndPunctuation //設置鍵盤類型
textField.delegate = self //將ViewController當前對象賦值給TextField控件的delegate委托屬性
self.view.addSubview(textField)
//textView代碼實現(xiàn)
let textViewWidth: CGFloat = 223
let textViewHeight: CGFloat = 198
let textViewTopView: CGFloat = 240
let textViewFrame = CGRect(x: (screen.size.width - textViewWidth)/2, y: textViewTopView, width: textViewWidth, height: textViewHeight)
let textView = UITextField(frame: textViewFrame)
textView.text = "green sky lalala"
textView.delegate = self//將ViewController當前對象賦值給TextView控件的delegate委托屬性
self.view.addSubview(textView)
}
//實現(xiàn)UITextFieldDelegate委托協(xié)議方法
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
print("TextField獲得焦點,點擊return鍵")
textField.resignFirstResponder() //放棄第一響應者身份,關閉鍵盤
return true
}
//實現(xiàn)UIViewFieldDelegate委托協(xié)議方法
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
if (text == "\n") {
print("TextView獲得焦點,點擊return鍵")
textView.resignFirstResponder()
return false
}
return true
}
//在關閉和打開鍵盤時,iOS系統(tǒng)會分別發(fā)出廣播通知.
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
//注冊鍵盤出現(xiàn)通知
NotificationCenter.default.addObserver(self, selector: #selector(keyboardDidShow(_:)), name: NSNotification.Name(rawValue: "showKeyboard") ,object: nil)
//注冊鍵盤隱藏通知
NotificationCenter.default.addObserver(self, selector: #selector(keyboardDidHide(_:)), name: NSNotification.Name(rawValue: "HideKeyboard"), object: nil)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
//注銷鍵盤出現(xiàn)通知
NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: "showKeyboard") ,object: nil)
//注銷鍵盤隱藏通知
NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: "HideKeyboard"), object: nil)
}
//butuon調(diào)用
@objc func onClick(_ sender: AnyObject){
self.label.text = "HelloWorld"
}
//viewWillAppear調(diào)用
@objc func keyboardDidShow(_ notification:Notification){
print("鍵盤打開")
}
@objc func keyboardDidHide(_ notification:Notification){
print("鍵盤關閉")
}
}
AppDelegate.swift部分:
// AppDelegate.swift
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
self.window = UIWindow(frame:UIScreen.main.bounds)
self.window?.rootViewController = ViewController()
self.window?.backgroundColor = UIColor.white
self.window?.makeKeyAndVisible()
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}