循环创建btn+使用imageEdgeInsets约束+设置图片大小

//设置btn的图片 标题 位置

-(void)addBtnsWithImages:(NSArray *)images btnTitles:(NSArray *)titles

{

    CGRect frame = self.containerView.frame;

    self.imageArray = images;

    self.titleArray = titles;

    CGFloat imageH = 30;

    CGFloat labWidth = frame.size.width/self.imageArray.count;

     for (int i = 0; i < self.imageArray.count; i++) {

         UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];

         btn.tag = DefaultTag + i;

         

         //获取图片

         NSString *imgUrl = [WPLUtil getWorkPlatformImgUrl:self.imageArray[i]];

         UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:imgUrl]]];

         //修改图片尺寸

         UIImage *newimage = [self imageWithImageSimple:image scaledToSize:CGSizeMake(imageH, imageH)];

         [btn setImage:newimage forState:UIControlStateNormal];

         

         //设置标题

         [btn setTitle:self.titleArray[i] forState:UIControlStateNormal];

         [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];

         btn.titleLabel.font = [UIFont systemFontOfSize:14];

         

         [btn addTarget:self action:@selector(clickBtnAction:) forControlEvents:UIControlEventTouchUpInside];

         

         [self.containerView addSubview:btn];


         btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;

         btn.contentVerticalAlignment = UIControlContentVerticalAlignmentTop;


         //获取 titleLabel size

         CGSize titleLabelSize = [btn.titleLabel.text sizeWithAttributes:@{NSFontAttributeName : btn.titleLabel.font}];

         //获取 imageView size

         [btn sizeToFit];

         CGSize imageViewSize = btn.imageView.frame.size;


         btn.frame = CGRectMake(labWidth *i, 16, labWidth, frame.size.height - 16*2);

         // button标题的偏移量

         btn.titleEdgeInsets = UIEdgeInsetsMake(imageViewSize.height + 16, (btn.frame.size.width - titleLabelSize.width) / 2.0 - imageViewSize.width, 0, 0);

         // button图片的偏移量

         btn.imageEdgeInsets = UIEdgeInsetsMake(8, (btn.frame.size.width - imageViewSize.width) / 2.0, 0, imageViewSize.width/2);

     }

}


- (UIImage *)imageWithImageSimple:(UIImage *)image scaledToSize:( CGSize )newSize

{

    UIGraphicsBeginImageContext(newSize);

    [image drawInRect:CGRectMake(0 ,0 ,newSize.width, newSize.height)];

    UIImage * newImage = UIGraphicsGetImageFromCurrentImageContext ();

    UIGraphicsEndImageContext ();

    return newImage;

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值