在进入自己的自定义视图类

时间:2018-03-10 21:33:34

标签: ios swift

我在Swift中以编程方式创建一个简单的视图,我有第一个工作正常的代码:

import UIKit

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = .darkGray

        let card:UIView = UIView()
        card.frame = CGRect(x: 38, y: 120, width: 300, height: 300)
        card.backgroundColor = .white
        card.layer.cornerRadius = 10
        card.layer.shadowOpacity = 0.5
        card.layer.shadowOffset = CGSize(width: 0, height: 10)
        card.layer.shadowRadius = 10

        view.addSubview(card)
    }
}

此代码生成此视图:

enter image description here

但我想重复使用这张卡,所以我将它放入一个新的类,如自定义视图,但卡现在消失了:

import UIKit

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = .darkGray

        let card = Card(frame: CGRect(x: 38, y: 120, width: 300, height: 300))

        view.addSubview(card)
    }
}

class Card:UIView {
    var box:UIView = UIView()

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupLayout()
    }

    func setupLayout(){
        box.backgroundColor = .white
        box.layer.cornerRadius = 10
        box.layer.shadowOpacity = 0.5
        box.layer.shadowOffset = CGSize(width: 0, height: 10)
        box.layer.shadowRadius = 10

        addSubview(box)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

你知道第二个代码有什么问题吗?

2 个答案:

答案 0 :(得分:0)

您的box并不知道应该在哪里绘制。添加这一行,它给它一个框架(原点和大小):

func setupLayout(){
    box.backgroundColor = .white
    box.layer.cornerRadius = 10
    box.layer.shadowOpacity = 0.5
    box.layer.shadowOffset = CGSize(width: 0, height: 10)
    box.layer.shadowRadius = 10
    // here's the line to add!
    box.frame = self.frame.insetBy(dx: 10.0, dy: 10.0)
    self.addSubview(box)
}

答案 1 :(得分:0)

这样更好:

func setupLayout(){
    box.backgroundColor = .white
    box.layer.cornerRadius = 10
    box.layer.shadowOpacity = 0.5
    box.layer.shadowOffset = CGSize(width: 0, height: 10)
    box.layer.shadowRadius = 10

    box.frame = self.frame
    self.addSubview(box)
}

它会自动从初始化程序中获取帧。