我正在尝试使用 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/