iOS开发——Swift自定义UIView

Home / iOS MrLee 2015-9-29 4416

在进行IOS开发的时候,有时候需要用到自定义View,下面来看看在Swift中,如何自定义UIView。
自定义UIView,首先我们需要继承UIView,并实现相应的方法。
最常用的是:
func drawRect(rect:CGRect) 这个是控件自身绘制的内容
func touchesBegan(touches: Set, withEvent event: UIEvent)  触摸事件开始
func touchesMoved(touches: Set, withEvent event: UIEvent)  触摸移动中
func touchesEnded(touches: Set, withEvent event: UIEvent)  触摸事件结束
func layoutSubviews()  对子控件布局进行精确控制
还有一系列其他的方法,大家可自行查阅文档。
下面我们来看一个简单的例子:
import UIKit
 
class MyView: UIView {
    var downColor = UIColor.redColor()
    var upColor = UIColor.blackColor()
    var nowColor:UIColor?
     
    override init(frame: CGRect) {
        super.init(frame:frame)
        self.backgroundColor = UIColor.clearColor()
        self.nowColor = upColor
    }
 
    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
     
    override func touchesBegan(touches: Set, withEvent event: UIEvent) {
        nowColor = downColor
        self.setNeedsDisplay()
    }
     
    override func touchesEnded(touches: Set, withEvent event: UIEvent) {
        nowColor = upColor
        self.setNeedsDisplay()
    }
     
    override func drawRect(rect: CGRect) {
        let ctx = UIGraphicsGetCurrentContext()
        CGContextClearRect(ctx, self.frame)
        CGContextSetFillColorWithColor(ctx, nowColor!.CGColor)
        CGContextFillEllipseInRect(ctx, CGRectMake(0, 0, self.frame.width, self.frame.height))
    }
}

 
上面是我们自己实现的一个UIView,主要是一个黑色的圆形,当触屏点击到它的时候,它变成红色,手指松开后,它继续变成黑色。
如下图:

QQ截图20150929105534

QQ截图20150929105523


主要是在绘制中,根据指定颜色绘制圆形,然后在触屏开始事件和触屏结束事件中,进行更改颜色。
仅供参考,大家可以自行试试
本文章为个人原创,转载请注明出处,个人博客地址:http://www.wjfxgame.com,本人CSDN博客:http://blog.csdn.net/wingfourever


趁着Android项目交付给别人测试的间隙开始学习Swift了,不得不说Swift里面很多语法设计确实很优秀,很方便,但是同样的也变复杂了。买了本书看了下,虽然现在Swift语法稳定了,但还是有不少地方改动了,不说别的,光是我这本书上运行失败的例子很多.....
不过还好,我也不是什么菜鸟开发者了,都是一些小问题,无关紧要。

本文链接:https://www.it72.com/6061.htm

推荐阅读
最新回复 (0)
返回