swift - 如何将 UIView 子类化并在其中添加另一个具有相同框架的 UIView

标签 swift uiview frame subclassing redraw

您好,我正在尝试通过继承 UIView 来创建自定义加载栏 View 。我想创建一个带有固定框架的 UIView 和其中的另一个 UIView 。当我初始化内部 UIView 时,通过此方法 override init(frame: CGRect) 传入的框架,这两个 View 具有不同的来源。我希望这两个 View 直接在彼此之上开始。我还希望能够通过调用 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
    }




}

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

最佳答案

对于您的内部 View ,您只需要来自父矩形的 widthheightxy 相对于父 View 应该为零:

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

关于swift - 如何将 UIView 子类化并在其中添加另一个具有相同框架的 UIView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40314613/

相关文章:

ios - 无法安装 Firebase iOS SDK (v3.2.0)

Swift/Spritekit UILongPressGestureRecognizer 似乎在按下时忽略所有其他手势

ios - UIView 坐标转换异常。转换点 : toView: not work well

ios - clipsToBounds 如何工作?

ios - 如何使 Swift 包在 Objective-C 项目中可导入/可用?

ios - Swift:如何从我的应用程序打开本地 pdf 到 iBooks

uiview - systemLayoutSizeFittingSize : require setNeedsLayout & layoutIfNeeded before it?

swift - CAGradientLayer 隐藏我的 UILabel 文本

java - 我如何用java制作蛇与梯子游戏的棋盘?

javascript - 使用 addEventListener/attachEvent 注册框架的 onload 事件