1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
| @implementation UIButton (LXMImagePosition)
- (void)setImagePosition:(LXMImagePosition)postion spacing:(CGFloat)spacing { CGFloat imageWith = self.imageView.image.size.width; CGFloat imageHeight = self.imageView.image.size.height; #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations"
#pragma clang diagnostic pop CGSize labelSize = CGSizeZero; CGFloat labelWidth = 0; CGFloat labelHeight = 0; if ([self.titleLabel.text respondsToSelector:@selector(boundingRectWithSize:options:attributes:context:)]) { labelSize = [self.titleLabel.text boundingRectWithSize:self.bounds.size options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:self.titleLabel.font} context:nil].size; }else { #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" labelSize = [self.titleLabel.text sizeWithFont:self.titleLabel.font]; #pragma clang diagnostic pop } labelWidth = labelSize.width; labelHeight = labelSize.height; CGFloat imageOffsetX = (imageWith + labelWidth) / 2 - imageWith / 2; CGFloat imageOffsetY = imageHeight / 2 + spacing / 2; CGFloat labelOffsetX = (imageWith + labelWidth / 2) - (imageWith + labelWidth) / 2; CGFloat labelOffsetY = labelHeight / 2 + spacing / 2; switch (postion) { case LXMImagePositionLeft: self.imageEdgeInsets = UIEdgeInsetsMake(0, -spacing/2, 0, spacing/2); self.titleEdgeInsets = UIEdgeInsetsMake(0, spacing/2, 0, -spacing/2); break; case LXMImagePositionRight: self.imageEdgeInsets = UIEdgeInsetsMake(0, labelWidth + spacing/2, 0, -(labelWidth + spacing/2)); self.titleEdgeInsets = UIEdgeInsetsMake(0, -(imageHeight + spacing/2), 0, imageHeight + spacing/2); break; case LXMImagePositionTop: self.imageEdgeInsets = UIEdgeInsetsMake(-imageOffsetY, imageOffsetX, imageOffsetY, -imageOffsetX); self.titleEdgeInsets = UIEdgeInsetsMake(labelOffsetY, -labelOffsetX, -labelOffsetY, labelOffsetX); break; case LXMImagePositionBottom: self.imageEdgeInsets = UIEdgeInsetsMake(imageOffsetY, imageOffsetX, -imageOffsetY, -imageOffsetX); self.titleEdgeInsets = UIEdgeInsetsMake(-labelOffsetY, -labelOffsetX, labelOffsetY, labelOffsetX); break; default: break; } }
@end
|