加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Swift 开发:自定义 GroupBox 案例

发布时间:2020-12-14 06:18:56 所属栏目:百科 来源:网络整理
导读: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;


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 效果图

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读