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

本文章讲解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("加载失败")
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 206,839评论 6 482
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 88,543评论 2 382
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 153,116评论 0 344
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 55,371评论 1 279
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 64,384评论 5 374
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,111评论 1 285
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,416评论 3 400
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,053评论 0 259
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 43,558评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,007评论 2 325
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,117评论 1 334
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,756评论 4 324
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,324评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,315评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,539评论 1 262
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,578评论 2 355
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,877评论 2 345

推荐阅读更多精彩内容