如何在swift中以编程方式创建自定义视图,具有控件文本字段,按钮等

时间:2015-03-13 10:55:21

标签: ios xcode swift custom-view

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

var view = MyCustomView(frame: CGRectZero)

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

我已经在当前ViewController的storyboard中设置了类。

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

5 个答案:

答案 0 :(得分:46)

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

但是,我希望你不要使用AutoLayout。因此,最简单的解决方案是通过明确提供框架来指定自定义视图的大小:

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

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

答案 1 :(得分:25)

Swift 3 / Swift 4 更新:

let screenSize: CGRect = UIScreen.main.bounds
let myView = UIView(frame: CGRect(x: 0, y: 0, width: screenSize.width - 10, height: 10))
self.view.addSubview(myView)

答案 2 :(得分:7)

var customView = UIView()


@IBAction func drawView(_ sender: AnyObject) {

    customView.frame = CGRect.init(x: 0, y: 0, width: 100, height: 200)
    customView.backgroundColor = UIColor.black     //give color to the view 
    customView.center = self.view.center  
    self.view.addSubview(customView)
       }

答案 3 :(得分:2)

view = MyCustomView(frame: CGRectZero)

在此行中,您尝试为自定义视图设置空矩形。这就是为什么你无法在模拟器中看到你的观点。

答案 4 :(得分:0)

let viewDemo = UIView()
viewDemo.frame = CGRect(x: 50, y: 50, width: 50, height: 50)
self.view.addSubview(viewDemo)