SoFunction
Updated on 2025-04-11

Swift code custom UIView implementation example

The principles of Swift custom View and OC custom View are the same. Rewrite the init() method or initWithFrame() method. Here is a brief description of how to customize the swift UIView

Mainly rewrite the init (frame: CGRect) method, where required init?(coder aDecoder: NSCoder) is essential, and is mandatory by the swift language

//
//  
//  SmartMilk
//
//  Created by mac on 2017/6/9.
// Copyright © 2017 mac. All rights reserved.//
import UIKit 
let G_HEADIMAGE_HEIGHT:CGFloat = 30 
class LoginImgFieldView: UIView {
    var headImgView:UIImageView?
    var field:UITextField?
    var line:UILabel?            
    /*
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        // Drawing code
    }
    */
//    override init(){
//        ()
//        setupSubViews()
//    }    
    override init(frame:CGRect){
        (frame: frame)
        setupSubViews()
    }    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }    
    func setupSubViews() {        
        let frame = 
        //uiimageVIew
        headImgView = UIImageView(frame:CGRect(x:0,y:0,width:G_HEADIMAGE_HEIGHT,height:G_HEADIMAGE_HEIGHT))
        headImgView?.backgroundColor = 
        
        //uiTextField
        field = UITextField(frame:CGRect(x:0,y:0,width:100,height:G_HEADIMAGE_HEIGHT))
//        field?.font = (ofSize: 15)        
        //uiLabel        
        line = UILabel(frame: CGRect(x:0,y:-1,width:,height:1))
        line?.backgroundColor =         
        (headImgView!)
        (field!)
        (line!)
    }       
    override func layoutSubviews() {
        ()        
        let frame = 
        let imgY = ( - G_HEADIMAGE_HEIGHT)/2
        headImgView?.frame = CGRect(x:0,y:imgY,width:G_HEADIMAGE_HEIGHT,height:G_HEADIMAGE_HEIGHT)        
        //field
        let fieldx = G_HEADIMAGE_HEIGHT+5
        let fieldWidth =  - fieldx        
        field?.frame = CGRect(x: fieldx, y: imgY, width: fieldWidth, height: G_HEADIMAGE_HEIGHT)        
        //label
        var lineFrame = line?.frame
        lineFrame?. =  - 2
        lineFrame?. =         
        line?.frame = lineFrame!
        
    }
 
}

This is the end of this article about Swift code custom UIView implementation examples. For more related Swift custom UIView content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!