2016-10-28 69 views
0

嗨我想通過繼承UIView來創建一個自定義加載欄視圖。我想創建一個帶有固定框架的UIView,以及其內部的另一個UIView。當我初始化內部UIView時,通過此方法傳入的幀override init(frame: CGRect),這兩個視圖具有不同的起源。我希望兩個觀點能夠直接相互展開。我也希望能夠通過調用這個uploadBar.setLoadingPercentage(percent: 53.5)你如何繼承UIView,並在同一幀內添加另一個UIView

這裏刷新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 
    } 




} 

The White bar is the view that I am subclassing the blue bar is <code>innerBar</code>

回答

1

對於您的內在視圖,您只需要父級rect中的widthheightxy應該相對於父視圖爲零:

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) 
}