您好,登錄后才能下訂單哦!
小編給大家分享一下Swift如何自定義UIView,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!
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. // 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! } }
以上是“Swift如何自定義UIView”這篇文章的所有內容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內容對大家有所幫助,如果還想學習更多知識,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。