问题描述
我正在尝试使用ViewController.swift中的以下代码从另一个类访问MyCustomView
.
I am trying to access the MyCustomView
from another class using the following code in ViewController.swift ..
var view = MyCustomView(frame: CGRectZero)
..在viewDidLoad
方法中.问题是视图未在模拟器中初始化.
.. in the viewDidLoad
method. The problem is the view does not get initialized in the simulator.
我已经在当前的ViewController的情节提要中设置了类.
I have already set class in storyboard for the current 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可以正确放置视图.
The CGRectZero
constant is equal to a rectangle at position (0,0)
with zero width and height. This is fine to use, and actually preferred, if you use AutoLayout, since AutoLayout will then properly place the view.
但是,我希望您不使用自动版式.因此,最简单的解决方案是通过显式提供框架来指定自定义视图的大小:
But, I expect you do not use AutoLayout. So the most simple solution is to specify the size of the custom view by providing a frame explicitly:
customView = MyCustomView(frame: CGRect(x: 0, y: 0, width: 200, height: 50))
self.view.addSubview(customView)
请注意,您还需要使用addSubview
,否则您的视图不会添加到视图层次结构中.
Note that you also need to use addSubview
otherwise your view is not added to the view hierarchy.
这篇关于如何以编程方式快速创建具有控件文本字段,按钮等的自定义视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!