gpt4 book ai didi

ios - 制作成自己的自定义 View 类时, View 不会出现

转载 作者:行者123 更新时间:2023-11-30 11:41:57 26 4
gpt4 key购买 nike

我正在 Swift 中以编程方式制作一个简单的 View ,我的第一个代码运行得很好:

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

这段代码使这个 View :

enter image description here

但是我想重用该卡,因此我将其放入一个新类(如自定义 View )中,但该卡现在消失了:

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

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

最佳答案

这样更好:

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

它自动从初始化器获取帧。

关于ios - 制作成自己的自定义 View 类时, View 不会出现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49214261/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com