Wing的小站

  • 首页
  • IT新闻
  • 技术文章
  • 生活随笔
  • 休闲娱乐
  • 个人作品
  • 留言板
  • 关于博主
JavaFX,Unity3D,Android,IOS,技术教程,生活随笔
  1. 首页
  2. 技术文章
  3. 正文

Swift自定义UIView

2015年9月10日 4640点热度 0人点赞 0条评论

在进行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
最后更新:2017年4月14日

wing1314

这个人很懒,什么都没留下

点赞
< 上一篇
下一篇 >

文章评论

razz evil exclaim smile redface biggrin eek confused idea lol mad twisted rolleyes wink cool arrow neutral cry mrgreen drooling persevering
取消回复

COPYRIGHT © 2023 Wing的小站. ALL RIGHTS RESERVED.

Theme Kratos Made By Seaton Jiang

鄂ICP备17006951号-1

42011102000591