[英]How do you subclass UIView and add another UIView inside of it with the same frame
嗨,我正在嘗試通過子類化UIView
來創建自定義加載欄視圖。 我想創建一個UIView
一個固定框架,另一個UIView
是它的內部。 當我初始化內部UIView
,通過此方法傳遞的框架override init(frame: CGRect)
,這兩個視圖的起源不同。 我希望這兩個視圖可以彼此直接位於頂部。 我還希望能夠通過調用此uploadBar.setLoadingPercentage(percent: 53.5)
來更新innerBar
這是代碼:
創建UploadBar
let uploadBar = UploadBar(frame: CGRect(x: 40, y: 40, width: 400, height: 40))
view.addSubview(uploadBar)
子類化UploadBar
import UIKit
class UploadBar: UIView {
var innerBar: UIView!
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = UIColor.white
innerBar = UIView(frame: frame)
innerBar.backgroundColor = UI.customBlue()
addSubview(innerBar)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setLoadingPercentage(percent: Double) {
// change innerBar's frame and redraw
}
}
對於內部視圖,您只需要父級矩形的width
和height
。 x
和y
相對於父視圖應為零:
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = UIColor.white
let innerRect = CGRect(x: 0, y: 0, width: frame.width, height: frame.height)
innerBar = UIView(frame: innerRect)
innerBar.backgroundColor = UI.customBlue()
addSubview(innerBar)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.