IOS基础002自定义控件

来源:互联网 发布:linux查看内存型号 编辑:程序博客网 时间:2024/06/03 12:26

通过绘图api来 编写控件

1创建一个ProgressController.swift  继承UIView

private  var _progressValue:CGFloat

public  func getProgressValue()->CGFloat{

return _progressValue

}

public func setProgressValue(value:CGFloat){

_progressValue = value

setNeedDisplay()//刷新绘图

}

override func drawRect(rect:CGRect){

     var ctx = UIGraphicsGetCurrentContext()//获取context

var r  = rect.width/2//获取半径

CGContextAddArc(context,r,r,r,0,3.141592653*2 ,0);画圆圈

CGContextSetRGBFillColor(ctx,0.7,0.7,0.7,1);//设置颜色

CGContextFillPath(ctx);//画图

CGContextAddArc(ctx,r,r,r,0,3.141592652*2*_progressValue)

CGContextSetRGBFillColor(ctx,1,0,1,1);//设置颜色

CGContextAddLineToPoint(,ctx,r,r)//连接圆弧与中点画线

CGContextFillPath(ctx)//画图

}


在ViewController里

var pc:ProgressCotrol

override func viewDidLoad(){

 pc = ProgressCotrol(frame:CGRect(x:100,y:100,width:100,height:100))

pc.setProgressValue(0.2)

self.view.addSubView(pc)

}


设置一个按钮,按钮的点击事件

@IBAction func addProgressBtnProgressed(sender:AnyObject){

pc.setProgressValue(pc.getProgressValue()+0.1)

}



实现预览自定义控件

创建类MyView继承UIView

@IBDesignable class  MyView :UIView     类要添加@IBDesignable     可设计的


@IBInspectable var str:Strin@IBInspectable var widthBorder:CGFloar = 0{   属性使用@IBInspectable  

didSet{  在storyboard中设置属性的时候会调用didset里的代码

layer.borderWidth = widthBorder    

}

}



IOS视图切换

在storyboard中添加两个view   设置图片   注:view与viewController在一层

在viewDidLoad(){

self.view.addSubview(img1)  //添加img1

}

点击屏幕出发事件

override func  touchesBegan(touches:NSSet!,widthEvent event:UIEvent!){

//运行后的回调函数

func completeHandler(value:Bool){

}

//动画效果  从img1翻转到img2

UIView.transitionFronView(img1,toView:img2,duration:1.0,

options:UIViewAnimationOptions.transitionFlipFromLeft,

completion:completeHandler)

    }



翻页效果

override func touchesBegan(touches:NSSet!,withEvent event:UIEvent!){

UIView.beginAnimations(nil,context:nil)//开始动画

UIView.setAnimationTransition(UIViewAnimationTransition.CurlDown,

forView:img1,cache:true)

UIView.setAnimationDuration(1.0) //设置动画

UIView.commitAnimations()//启动动画

}

自定义动画

override func touchesBegan(touches:NSSet!,withEvent event:UIEvent){

func  anim(){

img1.alpha = 0.5

img1.center = CGPoint(x:50,y:200)

}

func completeHandler(v:Bool){

println("complete")

}

UIView.transitionWithView(img1,duration:1.0,options:UIViewAnimationOptions.TransitionNone,

animations:anim,completion:completeHandler)


}





0 0
原创粉丝点击