美文网首页
iOS 用Swift自定义封装一个View(兼容OC)

iOS 用Swift自定义封装一个View(兼容OC)

作者: 微风_10a5 | 来源:发表于2022-03-23 16:22 被阅读0次

直接上干货,先来看最终效果:

基础款
[图片上传中...(iShot2022-03-23 15.32.09.gif-100630-1648021552876-0)]

基础款打印日志如下:


basic.png
升级款

1.文字与图片中间有间距,更加美观
2.左对齐,点击后不会闪动,
3.兼容OC工程,可以直接拖到OC工程里面使用,
4.回调使用枚举,更加直观

iShot2022-03-23 15.32.09.gif

升级款打印日志如下:

super.png

写这篇文章的缘由,之前都是用OC语言来封装一些控件,现在项目需要慢慢切换到Swift语言,由此而来,就需要使用swift语言来封装一些控件,用来记录封装的过程,同时希望对小伙伴们有所帮助

基础款封装代码如下:

//
//  OWCustomConfigView.swift
//  CustomView
//
//  Created by ZZ on 2022/3/23.
//

import Foundation
import UIKit

open class OWCustomConfigView : UIView {
    
    var selectedIndex = 0
    var buttonsClickIndex : ((Int)->())?
    
    init(titles:[String], selectedIndex:Int, buttonsClickIndex:@escaping (Int)->()) {
        super.init(frame: CGRect.zero)
        self.selectedIndex = selectedIndex
        self.buttonsClickIndex = buttonsClickIndex
        var couter = 0;
        let btnHeight = 60.0
        let btnWidth = 150.0

        for item in titles {
            let button = UIButton()
            button.frame = CGRect(x: 0, y: btnHeight*Double(couter), width: btnWidth, height: btnHeight)
            button.setTitle(item, for: .normal)
            
            button.backgroundColor = .red
            button.tag = couter
            button.addTarget(self, action: #selector(buttonClick(button:)), for: .touchUpInside)
            couter += 1
            self.addSubview(button)
        }
        for view in self.subviews {
//            print("button tag is \(view.tag)")
            let button = view as! UIButton
            
            if button.tag == selectedIndex {
                button.setImage(UIImage(named: "successArrow"), for: .normal)
            }else {
                button.setImage(UIImage(named: ""), for: .normal)
                
            }
        }
        
    }
    
    required public init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    @objc func buttonClick(button:UIButton) {
        let tag = button.tag
//        print("tag= \(tag)")
        guard let desButtonsClickIndex = self.buttonsClickIndex else { return  }
        desButtonsClickIndex(tag)
        
        
        //        另一种效果
        for view in self.subviews {
//            print("button tag is \(view.tag)")
            let button = view as! UIButton
            
            if button.tag == tag {
                button.setImage(UIImage(named: "successArrow"), for: .normal)
            }else {
                button.setImage(UIImage(named: ""), for: .normal)
                
            }
        }
        
    }
}

使用的地方:

//
//  ViewController.swift
//  CustomView
//
//  Created by ZZ on 2022/3/23.
//

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .purple        
        
        let titles = ["蓝牙模式","WIFI模式","AP模式"]
        
        let myView = OWCustomConfigView(titles: titles, selectedIndex: 0) { index in
            print("selected index: \(index)")
            
            switch index {
            case 0:
                print("ble")
            case 1:
                print("wifi")
            case 2:
                print("ap")
            default:
                print("ble")

            }
        }
        myView.frame = CGRect(x: 100, y: 100, width: 200, height: 300)
        
        view.addSubview(myView)
        // Do any additional setup after loading the view.
    }
 
}

升级款封装代码如下:

//
//  OWCustomConfigView.swift
//  CustomView
//
//  Created by ZZ on 2022/3/23.
//

import Foundation
import UIKit

@objc enum ConfigMode :Int {
    case ble = 0
    case wifi
    case ap
}

@objcMembers
open class OWCustomConfigView : UIView {
    
    var selectedMode = ConfigMode.ble
    var clickMode : ((ConfigMode)->())?
    let btnHeight = 60.0
    let btnWidth = 150.0
    init(titles:[String], selectedMode:ConfigMode = .ble, clickedMode:@escaping (ConfigMode)->()) {
        super.init(frame: CGRect(x: 0, y: 0, width: btnWidth, height: btnHeight*Double(titles.count)))
        self.selectedMode = selectedMode
        self.clickMode = clickedMode
        var couter = 0;

        
        for item in titles {
            let button = UIButton()
            button.frame = CGRect(x: 0, y: btnHeight*Double(couter), width: btnWidth, height: btnHeight)
            button.setTitle(item, for: .normal)
          
            button.backgroundColor = .gray
            button.contentHorizontalAlignment = .left
            button.titleEdgeInsets = UIEdgeInsets.init(top: 0, left: 40, bottom: 0, right: 0)
            button.imageEdgeInsets = UIEdgeInsets.init(top: 0, left: 20, bottom: 0, right: 0)

            button.tag = couter
            button.addTarget(self, action: #selector(buttonClick(button:)), for: .touchUpInside)
            couter += 1
            self.addSubview(button)
        }
        for view in self.subviews {
            //            print("button tag is \(view.tag)")
            let button = view as! UIButton
            
            if button.tag == selectedMode.rawValue {
                button.setImage(UIImage(named: "successArrow"), for: .normal)
            }else {
                button.setImage(UIImage(named: "successArrowHidden"), for: .normal)

            }
        }
        
    }
    
    public override init(frame: CGRect) {
        super.init(frame: frame)
    }
    
    required public init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    @objc func buttonClick(button:UIButton) {
        let tag = button.tag
        //        print("tag= \(tag)")
        guard let desButtonsClickedMode = self.clickMode else { return  }
        desButtonsClickedMode(ConfigMode(rawValue: tag)!)
        
        
        //        另一种效果
        for view in self.subviews {
            //            print("button tag is \(view.tag)")
            let button = view as! UIButton
            
            if button.tag == tag {
                button.setImage(UIImage(named: "successArrow"), for: .normal)
            }else {
                button.setImage(UIImage(named: "successArrowHidden"), for: .normal)
                
            }
        }
        
    }
}

其中@objc@objcMembers等关键字是为了兼容OC工程,方便在OC工程中使用

进阶款使用的地方:

//
//  ViewController.swift
//  CustomView
//
//  Created by ZZ on 2022/3/23.
//

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .purple
        
        let titles = ["蓝牙模式","WIFI模式","AP模式"]
        
        let myView = OWCustomConfigView(titles: titles, selectedMode: .ble) { mode in
            print("selected index: \(mode.rawValue)")

            switch mode {
            case .ble:
                print("ble")
                
            case .wifi:
                print("wifi")

            case .ap:
                print("ap")

            }

        }
        
        myView.frame = CGRect(x: 100, y: 100, width: 200, height: 400)
        view.addSubview(myView)
        // Do any additional setup after loading the view.
    }
    
}

结尾

今天的分享至此接近尾声喽,小伴们,觉得有点用的话,或者已经看到这里面来的请点赞加关注吧~~ 后续分享更多iOS原生技术及物联网技术相关文章。如果有疑问的话,欢迎在下方留言~

相关文章

网友评论

      本文标题:iOS 用Swift自定义封装一个View(兼容OC)

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