swift 4.2用代码实现label,button,textfield,textview

本文详细介绍如何在SwiftUI中创建和布局基本UI组件,包括UILabel、UIButton、UITextField和UITextView,并实现键盘事件监听和响应。通过代码示例,展示了组件的初始化、布局设置、事件处理及键盘操作。

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代码实现
        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代码实现
        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,第一个参数是事件处理者,第二个参数是选择器类型,它指向事件处理方法,第三个参数是事件.
        button.addTarget(self, action: #selector(onClick(_:)), for: UIControl.Event.touchUpInside)
        self.view.addSubview(button)
        
        
        //textfield和textview在模拟器要弹出软键盘,需要先在模拟器菜单“Hardware”---“keyboard”---“Connect Hardware Keyboard”,去掉勾选.
        //textfield代码实现
        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代码实现
        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)
        
        
    }
    
    
    //实现UITextFieldDelegate委托协议方法
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        print("TextField获得焦点,点击return键")
        textField.resignFirstResponder() //放弃第一响应者身份,关闭键盘
        return true
    }
    
    //实现UIViewFieldDelegate委托协议方法
    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        if (text == "\n") {
            print("TextView获得焦点,点击return键")
            textView.resignFirstResponder()
            return false
        }
        return true
    }
    
    //在关闭和打开键盘时,iOS系统会分别发出广播通知.
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        //注册键盘出现通知
        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)
        //注销键盘出现通知
        NotificationCenter.default.removeObserver(self,  name: NSNotification.Name(rawValue: "showKeyboard") ,object: nil)
        //注销键盘隐藏通知
        NotificationCenter.default.removeObserver(self, name:  NSNotification.Name(rawValue: "HideKeyboard"), object: nil)
        
    }
    
    //butuon调用
    @objc func onClick(_ sender: AnyObject){
        self.label.text = "HelloWorld"
    }
    
    //viewWillAppear调用
    @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:.
    }


}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值