//设置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;
}