swift代码自定义uiview实现示例-kb88凯时官网登录

来自:网络
时间:2023-07-25
阅读:

swift自定义view和oc自定义view的原理都是一样的,重写init()方法或initwithframe()方法,下面简单说说如何自定义swift uiview

主要是重写init(frame:cgrect)方法,其中required init?(coder adecoder: nscoder) 是必不可少的,swift语言强制要求的

//
//  loginimgfieldview.swift
//  smartmilk
//
//  created by mac on 2017/6/9.
//  d88尊龙官网手机app 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(){
//        super.init()
//        setupsubviews()
//    }    
    override init(frame:cgrect){
        super.init(frame: frame)
        setupsubviews()
    }    
    required init?(coder adecoder: nscoder) {
        fatalerror("init(coder:) has not been implemented")
    }    
    func setupsubviews() {        
        let frame = self.bounds
        //uiimageview
        headimgview = uiimageview(frame:cgrect(x:0,y:0,width:g_headimage_height,height:g_headimage_height))
        headimgview?.backgroundcolor = uicolor.blue
        
        //uitextfield
        field = uitextfield(frame:cgrect(x:0,y:0,width:100,height:g_headimage_height))
//        field?.font = uifont.systemfont(ofsize: 15)        
        //uilabel        
        line = uilabel(frame: cgrect(x:0,y:frame.size.height-1,width:frame.size.width,height:1))
        line?.backgroundcolor = uicolor.orange        
        self.addsubview(headimgview!)
        self.addsubview(field!)
        self.addsubview(line!)
    }       
    override func layoutsubviews() {
        super.layoutsubviews()        
        let frame = self.bounds
        let imgy = (frame.size.height - 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 = frame.size.width - fieldx        
        field?.frame = cgrect(x: fieldx, y: imgy, width: fieldwidth, height: g_headimage_height)        
        //label
        var lineframe = line?.frame
        lineframe?.origin.y = frame.size.height - 2
        lineframe?.size.width = frame.size.width        
        line?.frame = lineframe!
        
    }
 
}
返回顶部
顶部
网站地图