您的位置:首页 > 移动开发 > Swift

Swift 开发:自定义 GroupBox 案例

2017-04-27 21:39 561 查看

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,
nil, space, space)

        

        //3 x =
间隔长度, y =
总高度 -
间隔长度
       CGPathAddLineToPoint(path,
nil, space, h - space)

        

        //4 x =
总宽度 -
间隔长度, y =
总高度 -
间隔长度
       CGPathAddLineToPoint(path,
nil, w - space , h - space)

        

        //5 x =
总宽度 -
间隔长度, y =
间隔长度
       CGPathAddLineToPoint(path,
nil, w - space , space)

        

        //6 x =
总宽度 -
间隔长度, y =
间隔长度
       CGPathAddLineToPoint(path,
nil,space +  drawEnd  , space)

        

        //添加到context中
       CGContextAddPath(context, path)

        CGContextSetRGBStrokeColor(context,1,
1,0,
1)

        CGContextStrokePath(context)

       
    }

    
}

2 调用方法

//

//  ViewController.swift

//  groupbox

//

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

//  Copyright © 2017年
黄涛. All rights reserved.

//

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

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐