你如何继承UIView并在其中添加另一个UIView与相同的框架

时间:2016-10-28 23:44:22

标签: swift uiview frame subclassing redraw

您好我正在尝试通过继承UIView来创建自定义加载栏视图。我想创建一个具有固定框架的UIView,以及另一个UIView内部的UIView。当我初始化内部override init(frame: CGRect)时,通过此方法innerBar传入的帧,两个视图具有不同的来源。我希望这两个视图直接在彼此之上开始。我还希望能够通过调用此uploadBar.setLoadingPercentage(percent: 53.5)

来更新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 } }

ws.send(JSON.stringify({ "type" : "message", "message" : "Hello" }));
ws.send(JSON.stringify({ "type" : "username_change", "newusername" : "John" }));

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

1 个答案:

答案 0 :(得分: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)
}