Swift 开发:自定义 GroupBox 案例


1 封装一个view

//

// UIGroupBox.swift

// groupBox

// Created by 开发 on 17/4/27.

// copyright © 2017 黄涛. All rights reserved.

//


import UIKit


class UIGroupBox :UIView {


func drawInfo(width:CGFloat,txt:Nsstring){

drawText = txt;

drawStart = 30;

drawEnd = width + 30;

}

var drawText:Nsstring ="";

var drawStart:CGFloat =0;

var drawEnd:CGFloat =0;

override func drawRect(rect:CGRect) {

self.backgroundColor =UIColor.grayColor();

let context =UIGraphicsGetCurrentContext()

//创建path

let path =CGPathCreateMutable()

let w:CGFloat =self.frame.width;

let h:CGFloat =self.frame.height;

let space:CGFloat =50;


let font2 = UIFont.boldSystemFontOfSize(16)

let dic:[String:AnyObject]? = [NSForegroundColorAttributeName:UIColor.whiteColor(),NSFontAttributeName :font2];

drawText.drawAtPoint(CGPoint(x:drawStart + space + 10,y: space - 10),withAttributes:dic);

//1 x = 开始位置 间隔长度, y 间隔长度

CGPathMovetoPoint(path,nil,drawStart + space,space)

//2 x = 间隔长度, y 间隔长度

CGPathAddLinetoPoint(path,space,0)"> //3 x = 间隔长度, y 总高度 间隔长度

CGPathAddLinetoPoint(path,h - space)

//4 x = 总宽度 间隔长度, y 总高度 间隔长度

CGPathAddLinetoPoint(path,w - space,0)"> //5 x = 总宽度 间隔长度, y 间隔长度

CGPathAddLinetoPoint(path,0)"> //6 x = 总宽度 间隔长度, y 间隔长度

CGPathAddLinetoPoint(path,space + drawEnd,0)"> //添加context

CGContextAddpath(context,path)

CGContextSetRGBstrokeColor(context,1,0,1)

CGContextstrokePath(context)

}

}


2 调用方法

// ViewController.swift

//


import UIKit


class ViewController: UIViewController {


@IBOutlet weak var mainView: UIView!

override func viewDidLoad() {

super.viewDidLoad()

mainView.layoutIfNeeded();

let Box = UIGroupBox();

Box.drawInfo(120,txt: "标题测试应用")

Box.frame = CGRectMake(0,0,mainView.frame.width,mainView.frame.height);

mainView.addSubview(Box);

}


override func didReceiveMemoryWarning() {

super.didReceiveMemoryWarning()

// dispose of any resources that can be recreated.

}

}


3 效果

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...