美文网首页swift
一天学完swift常用控件基本用法

一天学完swift常用控件基本用法

作者: joymake | 来源:发表于2019-08-26 11:46 被阅读0次

    本文章讲解swift的基本控件基本方法,以下控件均为懒加载写法,您可以照着联想出oc中的功能

    1.UILabel                        文本标签
    2.UIImageView                    图片
    3.UITextField                    文本编辑
    4.UIButton                       按钮
    5.UITextView                     可滚动文本编辑
    6.UISwitch                       开关
    7.UIStepper                      步进器
    8.UISlider                       滑动控件
    9.UIProgressView                 进度条
    10.UISegmentedControl            标签控件
    11.UIActivityIndicatorView       网络状态控件
    12.UIDatePicker                  日期选择器
    13.UITableView                   列表视图
    14.UICollectionView              九宫格视图
    15.WKWebView                     web视图
    
    image.png
    image.png

    1.UILabel 文本标签

    lazy var versionLabel : UILabel = {
            let versionLabel = UILabel()
            versionLabel.font = UIFont(name:"Zapfino", size:10)
            versionLabel.textAlignment = .center
            versionLabel.shadowColor = UIColor.gray  //灰色阴影
            versionLabel.shadowOffset = CGSize(width:1.5, height:1.5)  //阴影的偏移量
            versionLabel.lineBreakMode = .byTruncatingTail
            let attributeString = NSMutableAttributedString(string:"welcome to swift")
            attributeString.addAttribute(NSAttributedString.Key.font, value: UIFont(name: "HelveticaNeue-Bold", size: 16)!, range: NSMakeRange(0,6))
            attributeString.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.blue, range: NSMakeRange(0, 3))
            attributeString.addAttribute(NSAttributedString.Key.backgroundColor, value: UIColor.green, range: NSMakeRange(3,3))
            versionLabel.attributedText = attributeString
            return versionLabel
        }()
    

    2.UIImageView 图片

        lazy var logoImgView : UIImageView = {
            let logoImgView = UIImageView()
            logoImgView.contentMode = .scaleAspectFill
            logoImgView.image = UIImage(named: "g3_portal_through_person")
            return logoImgView
        }()
    

    3.UITextField 文本编辑

      lazy var nameTextField : UITextField = {
            let nameTextField = UITextField()
            nameTextField.placeholder = "请输入用户手机号"
            nameTextField.borderStyle = UITextField.BorderStyle.roundedRect
            nameTextField.keyboardType = UIKeyboardType.numberPad
            nameTextField.delegate = self
            nameTextField.returnKeyType = .done
            return nameTextField;
        }()
    
    //代理
        func textFieldShouldReturn(_ textField: UITextField) -> Bool {
            if(passwordTextField.text?.isEqual("dd") ?? false){
                print("11");
            }
            if((passwordTextField.text?.isEqual("ee"))! ){
                print("相等")
            }
            
            print(textField.text ?? "")
            return true
        }
        
        func textFieldDidEndEditing(_ textField: UITextField, reason: UITextField.DidEndEditingReason) {
            print(textField.text ?? "")
        }
    

    4.UIButton 按钮

        lazy var loginBtn : UIButton = {
            let loginBtn = UIButton()
            loginBtn.setTitle("登录", for: .normal)
            loginBtn.setTitleColor(UIColor.orange, for: .normal)
            loginBtn.setTitleColor(UIColor.green, for: .selected)
            loginBtn.addTarget(self, action: #selector(testAction(button:)), for: .touchUpInside)
            loginBtn.layer.borderColor = UIColor.orange.cgColor;
            loginBtn.layer.masksToBounds = true;
            loginBtn.layer.borderWidth = 0.5;
            loginBtn.layer.cornerRadius = 30;
            loginBtn.titleEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: -20)
            loginBtn.imageEdgeInsets = UIEdgeInsets(top: -10, left: -20, bottom: -10, right: 0)
            loginBtn.setImage(UIImage(named: "g3_portal_through_person"), for: .normal)
            loginBtn.titleLabel?.font = UIFont.boldSystemFont(ofSize: 16)
            return loginBtn
        }()
    
    //🔘事件
        @objc func testAction(button:UIButton){
            button.isSelected = !button.isSelected;
    //        LoginNetRequest.login(self.nameTextField.text! as NSString, self.passwordTextField.text! as NSString) { [weak self] in
                let nextVC = NextVC()
                self.navigationController?.pushViewController(nextVC, animated: true)
                LoginNetRequest.getUserInfo(success: {(response) in
                    print(response)
                })
    //        }
        }
    
    

    5.UITextView 可滚动文本编辑

        lazy var infoTextView : UITextView = {
            let infoTextView = UITextView()
            infoTextView.layer.borderColor = UIColor.orange.cgColor
            infoTextView.layer.cornerRadius = 5
            infoTextView.layer.borderWidth = 1
            infoTextView.textAlignment = .center
            infoTextView.isEditable = false
            infoTextView.isSelectable = true
            infoTextView.dataDetectorTypes = .all
            infoTextView.textContainerInset = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
            infoTextView.text = "从明天起,做一个幸福的人\n喂马,劈柴,周游世界\n从明天起,关心粮食和蔬菜\n我有一所房子,面朝大海,春暖花开\n从明天起,和每一个亲人通信\n告诉他们我的幸福\n那幸福的闪电告诉我的\n我将告诉每一个人\n给每一条河每一座山取一个温暖的名字\n phone:13859222222,\n link:https://www.baidu.com"
            let wx = UIMenuItem(title: "微信", action: #selector(openWX))
            let menu = UIMenuController()
            menu.menuItems = [wx]
            return infoTextView
        }()
    

    6.UISwitch 开关

        lazy var swiftSwitch: UISwitch = {
            let swiftSwitch = UISwitch()
            swiftSwitch.onTintColor = UIColor.purple
            swiftSwitch.tintColor = UIColor.blue
            swiftSwitch.thumbTintColor = UIColor.orange
            swiftSwitch.addTarget(self, action: #selector(switchDidChanged(_ :)), for: .valueChanged)
            return swiftSwitch
        }()
    
    //开关事件
        @objc func switchDidChanged(_ switch:UISwitch) {
            print("switchValueChanged")
        }
    
    

    7.UIStepper 步进器

        lazy var stepper: UIStepper = {
            let stepper = UIStepper()
            stepper.maximumValue = 10
            stepper.minimumValue = 2
            stepper.stepValue = 2
            stepper.isContinuous = true //是否可以按住不放步进
            stepper.wraps = true //是否允许循环
            stepper.addTarget(self, action: #selector(stepperValueChanged(_ :)), for: .valueChanged)
            stepper.transform = CGAffineTransform(scaleX: 1.0, y: 1.0)          //放大缩小视图
            //        stepper.setDecrementImage(UIImage(named:"voice-"), for: .normal)
            //        stepper.setIncrementImage(UIImage(named:"voice+"), for: .normal)
            //        stepper.setDividerImage(UIImage(named:"divider"), forLeftSegmentState: .normal, rightSegmentState: .normal)
            return stepper
        }()
    
    //步进器事件
        @objc func stepperValueChanged(_ stepper:UIStepper){
            print(stepper.value)
        }
    
    

    8.UISlider 滑动控件

        lazy var slider: UISlider = {
            let slider = UISlider()
            slider.minimumValue = 0
            slider.maximumValue = 1
            slider.value = 0.3
            slider.minimumTrackTintColor = UIColor.green
            slider.maximumTrackTintColor = UIColor.orange
            //        slider.minimumValueImage = UIImage(named:"voice-")  //左边图标
            //        slider.maximumValueImage = UIImage(named:"voice+")  //右边图标
            //        slider.setThumbImage(UIImage(named:"voice"), for: .normal)//设置滑块图片
            slider.addTarget(self, action: #selector(sliderValueChanged(_ :)), for: .valueChanged)
            return slider
        }()
    
    //slider事件
        @objc func sliderValueChanged(_ slider:UISlider){
            print(slider.value)
        }
    

    9.UIProgressView 进度条

        lazy var progress: UIProgressView = {
            let progress = UIProgressView(progressViewStyle: UIProgressView.Style.default)
            progress.trackTintColor = UIColor.red
            progress.progressTintColor = UIColor.green
            progress.tintColor = UIColor.orange
            progress.setProgress(0.7, animated: true)
            return progress
        }()
    

    10. UISegmentedControl分段控制器

        lazy var segment: UISegmentedControl = {
            let items = ["昨天","今天","明天"]
            let segment = UISegmentedControl(items: items)
            segment.selectedSegmentIndex = 1
            segment.addTarget(self, action: #selector(segmentChanged(_ :)), for: .valueChanged)
            return segment
        }()
    //分段控制器事件
        @objc func segmentChanged(_ segment: UISegmentedControl) {
            print(segment.selectedSegmentIndex)
        }
    
    

    11.UIActivityIndicatorView 网络状态控件

        lazy var activity: UIActivityIndicatorView = {
           let activity = UIActivityIndicatorView.init(style: UIActivityIndicatorView.Style.gray)
            activity.tintColor = UIColor.orange
            activity.color = UIColor.green
            activity.frame = CGRect(x: 10, y: 100, width: 100, height: 100)
           return activity
        }()
    
    //开始转动
     activity.startAnimating()
    

    12.UIDatePicker 日期选择器

        lazy var pickView: UIDatePicker = {
            let pickView = UIDatePicker()
            pickView.datePickerMode = .date
            return pickView
        }()
    

    13.UITableView 列表视图

    class NextVC: UIViewController ,UITableViewDelegate,UITableViewDataSource
    //*************************************************
        lazy var dataList: NSMutableArray = {
            let dataList = NSMutableArray.init(objects: "财经","新闻","直播","运动","娱乐","军事","生活","体育","国际")
            return dataList
        }()
    
        lazy var tableView : UITableView = {
            let tableView = UITableView.init(frame: CGRect(x: 0, y: 0, width:self.view.bounds.size.width, height: 200), style: .grouped)
    
    /*
            let clsName = Bundle.main.infoDictionary!["CFBundleExecutable"] as? String//这是获取项目的名称,
            let className=clsName! + "." + "NextTableCell"
            let cellClass = NSClassFromString(className)!as! UITableViewCell.Type
            tableView.register(cellClass.classForCoder(), forCellReuseIdentifier: "NextTableCell")
    */
    //注册cell也可以用以下方法,封装table时可以通过以上string转class的方法实现
            tableView.register(NextTableCell.self, forCellReuseIdentifier: "NextTableCell")
    
            tableView.delegate = self
            tableView.dataSource = self
            return tableView
        }()
    
    
    //table常用代理
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return dataList.count
        }
        
        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let identifier : String = "NextTableCell"
    /*
            let cell:UITableViewCell = tableView.dequeueReusableCell(withIdentifier: identifier, for: indexPath)
            let protocolCell:JoyTableProtocol = cell as! JoyTableProtocol
    */
    以上方法用于按协议封装cell时使用,以下为直接复用已知类型cell时使用
            let protocolCell:NextTableCell = tableView.dequeueReusableCell(withIdentifier: "NextTableCell", for: indexPath)as! NextTableCell
            let model = dataList[indexPath.row]
            protocolCell.setCellModel(model)
            return cell 
        }
        
        func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
            pickView.isHidden = !pickView.isHidden
        }
        
        func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
            return 40
        }
    
    //tableCell
    class NextTableCell: UITableViewCell, JoyTableProtocol {
    
        var nameLabel: UILabel = {
            let nameLabel = UILabel()
            nameLabel.textColor = UIColor.orange
            nameLabel.font = UIFont.systemFont(ofSize: 14)
            return nameLabel
        }()
        
        override func awakeFromNib() {
            super.awakeFromNib()
            // Initialization code
        }
        
        required init?(coder aDecoder: NSCoder) {
            super.init(coder: aDecoder)
        }
        
        override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
            super.init(style: style, reuseIdentifier: reuseIdentifier)
            self.addSubViews()
        }
        
        func addSubViews() {
            nameLabel.frame = CGRect(x: 15, y: 10, width: 200, height: 20)
            self.contentView.addSubview(nameLabel)
        }
        
        func setCellModel(_ model: Any) {
            nameLabel.text = (model as! String)
        }
        
        override func setSelected(_ selected: Bool, animated: Bool) {
            super.setSelected(selected, animated: animated)
    
            // Configure the view for the selected state
        }
    
    }
    

    14.UICollectionView 九宫格视图

    class NextVC: UIViewController UICollectionViewDataSource,UICollectionViewDelegate
    //*************************************************
        lazy var collectionLayout: UICollectionViewFlowLayout = {
            let collectionLayout = UICollectionViewFlowLayout.init()
            collectionLayout.itemSize = CGSize(width: 80, height: 80)
            collectionLayout.minimumLineSpacing = 15
            collectionLayout.minimumInteritemSpacing = 15
            collectionLayout.scrollDirection = .vertical
            collectionLayout.sectionInset = UIEdgeInsets.init(top: 5, left: 5, bottom: 5, right: 5)
            // 设置分区头视图和尾视图宽高
    //        collectionLayout.headerReferenceSize = CGSize.init(width: 375, height: 80)
    //        collectionLayout.footerReferenceSize = CGSize.init(width: 375, height: 80)
            return collectionLayout
        }()
        
        lazy var collectionView : UICollectionView = {
            
            let collectionView = UICollectionView.init(frame:  CGRect(x: 0, y: 200, width:self.view.bounds.size.width, height: 200), collectionViewLayout: collectionLayout)
            let clsName = Bundle.main.infoDictionary!["CFBundleExecutable"] as? String//这是获取项目的名称,
            let className=clsName! + "." + "NextCollectionCell"
            let cellClass = NSClassFromString(className)!as! UICollectionViewCell.Type
            
            collectionView.register(cellClass.classForCoder(), forCellWithReuseIdentifier: "NextCollectionCell")
            collectionView.delegate = self
            collectionView.dataSource = self
            return collectionView
        }()
    
      //collection 代理
        func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
            return dataList.count
        }
        
        func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
            let cell:NextCollectionCell = collectionView.dequeueReusableCell(withReuseIdentifier: "NextCollectionCell", for: indexPath) as! NextCollectionCell
            let name = dataList[indexPath.row]
            cell.setCellModel(name as! NSString)
            return cell
        }
        
        func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
            let webVC = WebVC()
            self.navigationController?.pushViewController(webVC, animated: true)
        }
    
    //collectioncell
    class NextCollectionCell: UICollectionViewCell {
        var nameLabel: UILabel = {
            let nameLabel = UILabel()
            nameLabel.textColor = UIColor.white
            nameLabel.font = UIFont.systemFont(ofSize: 14)
            nameLabel.textAlignment = .center
            return nameLabel
        }()
    
        
        required init?(coder aDecoder: NSCoder) {
            super.init(coder: aDecoder)
        }
        
        override init(frame: CGRect) {
            super.init(frame: frame)
            self.addSubViews()
        }
        func addSubViews() {
            nameLabel.frame = CGRect(x: 10, y: 10, width: 60, height: 60)
            self.contentView.addSubview(nameLabel)
        }
        
        func setCellModel(_ name:NSString) {
            nameLabel.text = name as String
            self.contentView.backgroundColor = self.armColor()
        }
    
        func armColor()->UIColor{
            let red = CGFloat(arc4random()%256)/255.0
            let green = CGFloat(arc4random()%256)/255.0
            let blue = CGFloat(arc4random()%256)/255.0
            return UIColor(red: red, green: green, blue: blue, alpha: 1.0)
        }
    }
    

    15.WKWebView web视图

    import UIKit
    import WebKit
    
    class WebVC: UIViewController ,WKNavigationDelegate{
        lazy var webView: WKWebView = {
            let webView = WKWebView()
            webView.navigationDelegate = self
            return webView
        }()
        
        override func viewDidLoad() {
            super.viewDidLoad()
            webView.frame = self.view.bounds
            let url = URL(string: "https://www.jianshu.com/p/a56addca1c6b")
            let request = URLRequest(url: url!)
            webView.load(request)
           
    //        webView.load(URLRequest.init(url: URL.init(string: "http://www.163.com")!))
            self.view.addSubview(webView)
        }
    
    
    //web delegate
        func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
            print("开始加载")
        }
        
        func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
            print("开始数据返回")
        }
        
        func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
            print("加载成功")
        }
        
        func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
            print("加载失败")
        }
    }
    

    相关文章

      网友评论

        本文标题:一天学完swift常用控件基本用法

        本文链接:https://www.haomeiwen.com/subject/ygtrectx.html