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();
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 效果图