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 效果图
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。