JavaFX,Unity3D,Android,IOS等技术教程和生活随笔,仅供记录

http://www.wingmei.cn/wp-content/themes/Vtrois-Kratos-e85a527/images/background.jpg

Swift自定义UIView

在进行IOS开发的时候,有时候需要用到自定义View,下面来看看在Swift中,如何自定义UIView。

自定义UIView,首先我们需要继承UIView,并实现相应的方法。

最常用的是:

func drawRect(rect:CGRect) 这个是控件自身绘制的内容

func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent)  触摸事件开始

func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent)  触摸移动中

func touchesEnded(touches: Set<NSObject>, 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,主要是一个黑色的圆形,当触屏点击到它的时候,它变成红色,手指松开后,它继续变成黑色。

如下图:

《Swift自定义UIView》 《Swift自定义UIView》

主要是在绘制中,根据指定颜色绘制圆形,然后在触屏开始事件和触屏结束事件中,进行更改颜色。

仅供参考,大家可以自行试试

点赞

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注