1.UILabel加阴影效果
因为label数据随时更新,所以换用NSMutableAttributedString:
NSShadow *shadow = [NSShadow new];
shadow.shadowColor = [MHColorUtils colorWithRGB:0x000000 alpha:0.28];
shadow.shadowBlurRadius = HLQF3scalePT(1);
shadow.shadowOffset = CGSizeMake(HLQF3scalePT(0.5), HLQF3scalePT(0.5));
UIFont *font = [UIFont fontWithName:@"PingFangSC-Medium" size:12];
NSMutableAttributedString tempString = [[NSMutableAttributedString alloc] initWithString:@"test" attributes:@{NSShadowAttributeName:shadow,NSFontAttributeName:font,NSForegroundColorAttributeName:[UIColor blackColor]}];
2.UIButton图片与文字位置处理
button显示图片和文字的规则:
1.当button.width < image.width时,只显示被压缩后的图片,图片是按fillXY的方式压缩。
2.当button.width > image.width,且 button.width < (image.width + text.width)时,图片正常显示,文本被压缩。
3.当button.width > (image.width+text.width),两者并列默认居中显示,可通过button的属性contentHorizontalAlignment改变对齐方式。
setTitleEdgeInsets和setImageEdgeInsets作用方式:
通过设置setTitleEdgeInsets和setImageEdgeInsets来改变控件位置时,需要注意的是,对titleLabel和imageView设置偏移,是针对它当前的位置起作用的,并不是针对它距离button边框的距离的。
button的对齐方式:
默认状态下,button的属性contentHorizontalAlignmen(水平对齐方式)和contentVerticalAlignment(竖直对齐方式)都是默认是居中的。所以button的image和label是紧贴着居中显示,图片在左,文字在右。所以如果我们直接在默认的对齐模式下设置,不仅计算具体数值时很麻烦,而且有文章说设置后的状态与设置的值会有偏差,不推荐使用这种方式。
推荐使用方法:
1.设置对齐方式,使图片和文字显示在button左上角,且图片在左。
//设置button对齐方式为水平居左,垂直居上
[btn setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
[btn setContentVerticalAlignment:UIControlContentVerticalAlignmentTop];
- 设置图片的边距。如果需要图片居中,图片需要向右偏移(btn.width-image.width)/2的距离,即图片的左边距将增加(btn.width-image.width)/2。
[btn setImageEdgeInsets:UIEdgeInsetsMake(0, (btn.width-image.width)/2, 0, 0)];
3.设置文字的边距。
在设置文字边距之前,如果不知道文字长度,需要先计算文字的宽度。文字需要向下偏移image.width+间距的距离,需要向右偏移(btn.width-label.width)/2-image.width的距离。如果文字实际是向左偏移了,这个方法将会计算出负数,不影响偏移结果。
//计算文字长度
NSDictionary *attributes = @{NSFontAttributeName:[UIFont systemFontOfSize:11]};
NSString *title=[btn titleForState:UIControlStateNormal];
float length = [title boundingRectWithSize:CGSizeMake(320, 2000) options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil].size.width;
//设置偏移量
float left = (btn.width-ceilf(length))/2-image.width;
float top = image.width+space;
[btn setTitleEdgeInsets:UIEdgeInsetsMake(top,left,0, 0)];