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

本文章講解swift的基本控件基本方法,以下控件均為懶加載寫法,您可以照著聯(lián)想出oc中的功能

1.UILabel                        文本標簽
2.UIImageView                    圖片
3.UITextField                    文本編輯
4.UIButton                       按鈕
5.UITextView                     可滾動文本編輯
6.UISwitch                       開關(guān)
7.UIStepper                      步進器
8.UISlider                       滑動控件
9.UIProgressView                 進度條
10.UISegmentedControl            標簽控件
11.UIActivityIndicatorView       網(wǎng)絡(luò)狀態(tài)控件
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從明天起,關(guā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 開關(guān)

    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
    }()

//開關(guān)事件
    @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 //是否允許循環(huán)
        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)//設(shè)置滑塊圖片
        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 網(wǎng)絡(luò)狀態(tài)控件

    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
    }()

//開始轉(zhuǎn)動
 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: "財經(jīng)","新聞","直播","運動","娛樂","軍事","生活","體育","國際")
        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轉(zhuǎn)class的方法實現(xiàn)
        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
*/
以上方法用于按協(xié)議封裝cell時使用,以下為直接復(fù)用已知類型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)
        // 設(shè)置分區(qū)頭視圖和尾視圖寬高
//        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: "http://www.itdecent.cn/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("開始數(shù)據(jù)返回")
    }
    
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        print("加載成功")
    }
    
    func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
        print("加載失敗")
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容