如何在swift中以编程方式创build自定义视图,并控制文本字段,button等
我正在尝试使用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) }
CGRectZero
常量等于位置(0,0)
处的长宽度为零的矩形。 如果使用AutoLayout,这样可以很好地使用,因为AutoLayout会正确放置视图。
但是,我希望你不要使用AutoLayout。 所以最简单的解决scheme是通过显式提供一个框架来指定自定义视图的大小:
customView = MyCustomView(frame: CGRect(x: 0, y: 0, width: 200, height: 50)) self.view.addSubview(customView)
请注意,您还需要使用addSubview
否则您的视图不会添加到视图层次结构中。
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)
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) }
view = MyCustomView(frame: CGRectZero)
在这一行中,您正尝试为您的自定义视图设置空的矩形。 这就是为什么你不能在模拟器中看到你的看法。