ios - 如何在具有控件文本字段、按钮等的 swift 中以编程方式创建自定义 View

标签 ios xcode swift custom-view

我正在尝试使用 ViewController.swift 中的以下代码从另一个类访问 MyCustomView ..

var view = MyCustomView(frame: CGRectZero)

.. 在 viewDidLoad 方法中。问题是 View 没有在模拟器中初始化。

我已经在 Storyboard中为当前的 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 会正确放置 View 。

但是,我希望您不要使用 AutoLayout。所以最简单的解决方案是通过显式提供框架来指定自定义 View 的大小:

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

请注意,您还需要使用 addSubview,否则您的 View 不会添加到 View 层次结构中。

关于ios - 如何在具有控件文本字段、按钮等的 swift 中以编程方式创建自定义 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29030426/

相关文章:

objective-c - 使用多个 NSSortDescriptor 有效地对数组中的对象进行排序

ios - 如何在 ios5 中更改 UINavigationbar 的高度

ios - 如何从 UIImagePickerController 选择多个图像

ios - 无法在 Collection View 中显示存储在 App Delegate 中的数组数据

swift - “ fatal error :在展开可选值时意外发现nil”是什么意思?

ios - 报告 UIView 子类所需大小的正确方法是什么?

ios - 将 "new" View 添加到没有 View 的应用程序中

Xcode 10 存档不包含任何产品

xcode - 分布式 dylib 的链接器设置

ios - 子类化 AFHTTPSessionManager 并使其成为 swift 中的单例