我试图使用ViewController中的以下代码从另一个类访问MyCustomView.敏捷的

var view = MyCustomView(frame: CGRectZero)

viewDidLoad法.问题是该视图没有在模拟器中初始化.

我已经在故事板中为当前的ViewController设置了类.

class MyCustomView: UIView {
    var label: UILabel = UILabel()
    var myNames = ["dipen","laxu","anis","aakash","santosh","raaa","ggdds","house"]

    override init(){
        super.init()
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        self.addCustomView()
    }

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

    func addCustomView() {
        label.frame = CGRectMake(50, 10, 200, 100)
        label.backgroundColor=UIColor.whiteColor()
        label.textAlignment = NSTextAlignment.Center
        label.text = "test label"
        label.hidden=true
        self.addSubview(label)

        var btn: UIButton = UIButton()
        btn.frame=CGRectMake(50, 120, 200, 100)
        btn.backgroundColor=UIColor.redColor()
        btn.setTitle("button", forState: UIControlState.Normal)
        btn.addTarget(self, action: "changeLabel", forControlEvents: UIControlEvents.TouchUpInside)
        self.addSubview(btn)

        var txtField : UITextField = UITextField()
        txtField.frame = CGRectMake(50, 250, 100,50)
        txtField.backgroundColor = UIColor.grayColor()
        self.addSubview(txtField)
    }

推荐答案

CGRectZero常数等于位置(0,0)处宽度和高度为零的矩形.如果使用AutoLayout,这是可以使用的,而且实际上是首选的,因为AutoLayout将正确放置视图.

但是,我希望您不使用自动布局.因此,最简单的解决方案是通过显式提供框架来指定自定义视图的大小:

customView = MyCustomView(frame: CGRect(x: 0, y: 0, width: 200, height: 50))
self.view.addSubview(customView)

请注意,还需要使用addSubview,否则视图不会添加到视图层次 struct 中.

Swift相关问答推荐

SwiftData:线程1:&Quot;NSFetchRequest找不到实体名称';提醒&q;的NSEntityDescription

SWIFT并发:合并Taskgroup和AsyncStream?

它是RxSwift中直接用于可扩展视图的有效的可扩展BehaviorRelay值?

编写Swift字符串的属性包装时遇到问题

如何将图像插入到矩形中

从任务中打印

文件命名&NumberForMatter+扩展名&:含义?

以编程方式使UIView居中,而不影响UIKit中其他UI类的位置

使用View()和List()无法显示影子

Swift 数组拆分成重叠的块

如何在 AppDelegate for Cocoa macOS 中创建 mainMenu 和菜单项?

在 macOS (Swift) 上获取 BSD 驱动器名称的最佳方法是什么?

SwiftUI 视图的默认成员初始化器 VS 自定义初始化器

如何有条件地依赖桌面与 iOS 的系统库?

试图同时实现两个混合过渡

无法分配给属性:absoluteString是一个只能获取的属性

AES 加密和解密

<<错误类型>> 奇怪的错误

如何在 Swift 中重写 setter

我可以让#selector 引用 Swift 中的闭包吗?