动态新增UIButton

作者: 熊猫小贼_ | 来源:发表于2016-08-01 17:40 被阅读0次

    因为工程中要用到,所以自己写了一个这样的控件
    实现比较简单,这里继承了UIButoon类 重写了这个方法

    • (CGRect)imageRectForContentRect:(CGRect)contentRect

    这里还有几个方法是对按钮的扩展

    具体实现参照如下:
    HomeMoreViewController.h文件

    #import <UIKit/UIKit.h>
    @interface MoreButton : UIButton
    @end
    
    @interface HomeMoreViewController : UIViewController
    @property (retain, nonatomic) NSMutableArray *listArr;
    
    @end
    

    HomeMoreViewController.m文件

    
    #import "HomeMoreViewController.h"
    
    @implementation MoreButton
    
    - (CGRect)imageRectForContentRect:(CGRect)contentRect{
        return CGRectMake((ScreenWidth/4-50)/2, 5, 50, 50);
    }
    @end
    
    @interface HomeMoreViewController ()
    
    @end
    
    @implementation HomeMoreViewController
    @synthesize FirstDelegate;
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        self.view.backgroundColor = [UIColor whiteColor];
        
        self.title = @"更多";
        UIColor * color = [UIColor blackColor];
        NSDictionary *attributes=[NSDictionary dictionaryWithObjectsAndKeys:color,NSForegroundColorAttributeName,nil];
        [self.navigationController.navigationBar setTitleTextAttributes:attributes];
        
        UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        backBtn.frame = CGRectMake(0, 0, 32, 32);
        backBtn.titleLabel.font = [UIFont fontWithName:imagefont size: 16];
        [backBtn setTitle:@"\U0000e80e" forState:UIControlStateNormal];
        [backBtn setTitleColor:key_BgColorF6E forState:UIControlStateNormal];
        backBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        [backBtn addTarget:self action:@selector(doBack:) forControlEvents:UIControlEventTouchUpInside];
        
        UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:backBtn];
        self.navigationItem.leftBarButtonItem = rightItem;
        
        
    
        float y = 64.0;
        float w = [UIScreen mainScreen].bounds.size.width;
        float h = 75;
        
        NSInteger num = self.listArr.count;//(ps:这里显示按钮的数量,我这边是api接口提供的数据,根据自己的项目需求来吧!)
        
        w = [UIScreen mainScreen].bounds.size.width/4;
        
        
        for (int i = 0; i<num; i++) {
            MoreButton *Btn = [MoreButton buttonWithType:UIButtonTypeCustom];
            Btn.frame = CGRectMake((i-(floor(i/4))*4)*w, y+(floor(i/4))*h, w, h);
            Btn.imageView.contentMode = UIViewContentModeScaleAspectFit;
            Btn.tag = i;
            Btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
            [Btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
            Btn.titleLabel.adjustsFontSizeToFitWidth=YES;
            [Btn addTarget:self action:@selector(setMethond:) forControlEvents:UIControlEventTouchUpInside];
            //缩略图
            NSString * imageStr = [NSString stringWithFormat:@"%@", [[self.listArr objectAtIndex:i] objectForKey:@"image"]];
            NSURL *imageurl = [NSURL URLWithString:imageStr];
            SDWebImageManager *manager = [SDWebImageManager sharedManager];
            [manager downloadImageWithURL:imageurl options:SDWebImageRetryFailed progress:^(NSInteger receivedSize, NSInteger expectedSize) {
            } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
                //                UIImage *myimage  = [self imageByScalingAndCroppingForSize:<#(CGSize)#> :<#(UIImage *)#>:image :CGSizeMake(50, 50)];
                UIImage *myimage = [self circleImageWithName:image borderWidth:1.0 borderColor:[UIColor whiteColor]];
               //这里可以对按钮进行图片的设置,我这里的图片资源是api接口提供  如果不需要设置按钮图片的话可以直接忽略这里的代码  直接在上面设置按钮的文字什么的
            }];
            Btn.clipsToBounds = YES;
            [self.view addSubview:Btn];
        }
    }
    
    - (void)doBack:(id)sender
    {
        [self.navigationController dismissViewControllerAnimated:YES completion:nil];
    }
    
    - (void)didReceiveMemoryWarning {
        [super didReceiveMemoryWarning];
        // Dispose of any resources that can be recreated.
    }
    
    - (void)setMethond:(UIButton *)sender{
       
    }
    
    - (UIImage *)circleImageWithName:(UIImage *)name borderWidth:(CGFloat)borderWidth borderColor:(UIColor *)borderColor
    {
        // 1.加载原图
        //    UIImage *oldImage = [self OriginImage:name scaleToSize:CGSizeMake(name.size.width*(iPhone5?0.67:1), name.size.height*(iPhone5?0.67:1))];
        UIImage *oldImage = name;
        // 2.开启上下文
        CGFloat imageW = oldImage.size.width ;
        CGFloat imageH = oldImage.size.height;
        CGSize imageSize = CGSizeMake(imageW, imageH);
        UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0.0);
        
        // 3.取得当前的上下文,这里得到的就是上面刚创建的那个图片上下文
        CGContextRef ctx = UIGraphicsGetCurrentContext();
        
        // 4.画边框(大圆)
        [borderColor set];
        CGFloat bigRadius = imageW * 0.5; // 大圆半径
        CGFloat centerX = bigRadius; // 圆心
        CGFloat centerY = bigRadius;
        CGContextAddArc(ctx, centerX, centerY, bigRadius, 0, M_PI * 2, 0);
        CGContextFillPath(ctx); // 画圆。As a side effect when you call this function, Quartz clears the current path.
        
        // 5.小圆
        CGFloat smallRadius = bigRadius - borderWidth;
        CGContextAddArc(ctx, centerX, centerY, smallRadius, 0, M_PI * 2, 0);
        // 裁剪(后面画的东西才会受裁剪的影响)
        CGContextClip(ctx);
        
        // 6.画图
        [oldImage drawInRect:CGRectMake(borderWidth, borderWidth, oldImage.size.width, oldImage.size.height)];
        
        // 7.取图
        UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
        
        // 8.结束上下文
        UIGraphicsEndImageContext();
        
        return newImage;
    }
    

    相关文章

      网友评论

        本文标题:动态新增UIButton

        本文链接:https://www.haomeiwen.com/subject/dzzxsttx.html