Swift 开发:自定义 GroupBox 案例

前端之家收集整理的这篇文章主要介绍了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 效果

原文链接:https://www.f2er.com/swift/321779.html

猜你在找的Swift相关文章