ios – 如何以编程方式创建自定义视图,具有控件文本字段,按钮等
发布时间:2020-12-15 02:03:12 所属栏目:百科 来源:网络整理
导读:我试图使用ViewController.swift中的以下代码从另一个类访问MyCustomView。 var view = MyCustomView(frame: CGRectZero) ..在viewDidLoad方法中。问题是在模拟器中没有初始化视图。 我已经在当前ViewController的storyboard中设置了类。 class MyCustomView
我试图使用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,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会自动正确放置视图,这是很好的使用,实际上是首选的。
但是,我希望你不要使用AutoLayout。因此,最简单的解决方案是通过明确提供一个框架来指定自定义视图的大小: customView = MyCustomView(frame: CGRect(top: 0,left: 0,width: 200,height: 50) self.view.addSubview(customView) 请注意,您还需要使用addSubview,否则视图未添加到视图层次结构中。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |