swift 4.2用代碼實現(xiàn)label,button,textfield,textview

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:.
    }


}
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末缺前,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子竣付,更是在濱河造成了極大的恐慌,老刑警劉巖古胆,帶你破解...
    沈念sama閱讀 206,214評論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件逸绎,死亡現(xiàn)場離奇詭異惹恃,居然都是意外死亡棺牧,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,307評論 2 382
  • 文/潘曉璐 我一進店門参淹,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人浙值,你說我怎么就攤上這事】牛” “怎么了?”我有些...
    開封第一講書人閱讀 152,543評論 0 341
  • 文/不壞的土叔 我叫張陵卵惦,是天一觀的道長瓦戚。 經(jīng)常有香客問我,道長伤极,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 55,221評論 1 279
  • 正文 為了忘掉前任庸疾,我火速辦了婚禮当编,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘忿偷。我一直安慰自己,他們只是感情好鲤桥,可當我...
    茶點故事閱讀 64,224評論 5 371
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著嫂拴,像睡著了一般贮喧。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上箱沦,一...
    開封第一講書人閱讀 49,007評論 1 284
  • 那天,我揣著相機與錄音灶伊,去河邊找鬼疆前。 笑死谁帕,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的匈挖。 我是一名探鬼主播康愤,決...
    沈念sama閱讀 38,313評論 3 399
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼择膝!你這毒婦竟也來了检激?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 36,956評論 0 259
  • 序言:老撾萬榮一對情侶失蹤叔收,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后窃页,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 43,441評論 1 300
  • 正文 獨居荒郊野嶺守林人離奇死亡脖卖,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 35,925評論 2 323
  • 正文 我和宋清朗相戀三年巧颈,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片十籍。...
    茶點故事閱讀 38,018評論 1 333
  • 序言:一個原本活蹦亂跳的男人離奇死亡晾嘶,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出垒迂,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 33,685評論 4 322
  • 正文 年R本政府宣布绣夺,位于F島的核電站欢揖,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏她混。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 39,234評論 3 307
  • 文/蒙蒙 一坤按、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧酗钞,春花似錦、人聲如沸砚作。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,240評論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽兼耀。三九已至,卻和暖如春瘤运,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背拯坟。 一陣腳步聲響...
    開封第一講書人閱讀 31,464評論 1 261
  • 我被黑心中介騙來泰國打工郁季, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留冷溃,地道東北人梦裂。 一個月前我還...
    沈念sama閱讀 45,467評論 2 352
  • 正文 我出身青樓,卻偏偏與公主長得像年柠,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子答憔,可洞房花燭夜當晚...
    茶點故事閱讀 42,762評論 2 345

推薦閱讀更多精彩內(nèi)容