http://blog.csdn.net/syg90178aw/article/details/47020097
自定义view
(一)常用的写法
-
-
- importUIKit
- privateletKLMargin:CGFloat=10
- KLLabelHeight:CGFloat=30
-
- classCustomView:UIView{
-
- varbuttonCallBack:(()->())?
- //重写init方法
- overrideinit(frame:CGRect){
- super.init(frame:frame)
- self.backgroundColor=UIColor.orangeColor()
- letlable:UILabel=UILabel(frame:CGRectMake(KLMargin,KLMargin,KLScreenWidth-(22*KLMargin),KLLabelHeight))
- lable.text="我丫就是一label"
- lable.textAlignment=NSTextAlignment.Center
- lable.backgroundColor=UIColor.lightGrayColor()
- self.addSubview(lable)
- letbutton:UIButton=UIButton.buttonWithType(UIButtonType.Custom)as!UIButton
- button.frame=CGRectMake(KLMargin,CGRectGetMaxY(lable.frame)+KLMargin,KLLabelHeight)
- button.backgroundColor=UIColor.lightTextColor()
- button.setTitle("俺是个按钮啊",forState:UIControlState.Normal)
- button.addTarget(self,0); background-color:inherit">action:Selector("buttonCllick:"),0); background-color:inherit">forControlEvents:UIControlEvents.TouchUpInside)
- button.layer.cornerRadius=5
- button.clipsToBounds=true
- self.addSubview(button)
- }
- //反正重写了init方法这个会根据提示自动蹦出来
- requiredinit(coderaDecoder:NSCoder){
- fatalError("init(coder:)hasnotbeenimplemented")
- }
- //按钮点击事件的调用
- funcbuttonCllick(button:UIButton){
- ifbuttonCallBack!=nil{
- buttonCallBack!()
- //重新绘制和oc里面效果一样(其实我也不是很明白)
- overridefuncdrawRect(rect:CGRect){
- //self.backgroundColor=UIColor.whiteColor()
- }
在其他类的调用
letcustomView:CustomView=CustomView(frame:CGRectMake(0,80,KLScreenWidth,KLScreenWidth/2))
- //闭包(block)的回调
- customView.buttonCallBack={()->()in
- customView.removeFromSuperview()
- self.view.addSubview(customView)
(二)在一开始的时候,我是写在drawRect里的,并没有重写init方法,发现也能实现效果
overridefuncdrawRect(rect:CGRect){
- self.backgroundColor=UIColor.orangeColor()
- lable.text="我丫就是一label"
- lable.textAlignment=NSTextAlignment.Center
- lable.backgroundColor=UIColor.lightGrayColor()
- self.addSubview(lable)
- button:UIButton=UIButton.buttonWithType(UIButtonType.Custom)as!UIButton
- button.frame=CGRectMake(KLMargin,KLLabelHeight)
- button.backgroundColor=UIColor.lightTextColor()
- button.setTitle("俺是个按钮啊",0); background-color:inherit">forState:UIControlState.Normal)
- button.addTarget(forControlEvents:UIControlEvents.TouchUpInside)
- button.layer.cornerRadius=5
- button.clipsToBounds=true
- self.addSubview(button)
- }
在其他类调用的时候,无法调用CustomView(frame:rect) 这个方法,只有像下面的代码那样调用
customView:CustomView=CustomView()
- customView.backgroundColor=UIColor.orangeColor()
- customView.frame=CGRectMake(0,KLScreenWidth/2)
- customView.buttonCallBack={()->()in
- customView.removeFromSuperview()
- self.view.addSubview(customView)
其实功能都能实现,但是毕竟drawRect只是绘制机制,控件的初始化,就不要在drawRect搞了,还是在init方法初始化吧 (编辑:李大同)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|