根据后台返回的UIButton title动态改变UIButton宽度

2018-06-05 15:22:35 浏览数 (3)

废话不多说代码见真章!!!

代码语言:javascript复制
#import <UIKit/UIKit.h>

@interface UIButton (MutableTitle)
/**
 *  根据添加的title 改变 button 的长度
 *
 *  @param text 
 */

- (void)setMutableTitleWithString:(NSString *)text textFont:(UIFont *)textFont forState:(UIControlState)UIControlState;
@end

#import "UIButton MutableTitle.h"

@implementation UIButton (MutableTitle)

- (void)setMutableTitleWithString:(NSString *)text textFont:(UIFont *)textFont forState:(UIControlState)controlState {
    CGSize tempSize = [self sizeForNoticeTitle:text font:textFont];
    [self setTitle:text forState:controlState];
    self.titleLabel.font = textFont;
    CGRect self_Rect = self.frame;
    self_Rect.size.width = tempSize.width;
    self_Rect.origin.x -= (tempSize.width - self.frame.size.width)/2;
    self.frame = self_Rect;
}

/**
 *  字符串获取属性
 *  @param text
 *  @param font
 *
 *  @return size
 */
- (CGSize)sizeForNoticeTitle:(NSString*)text font:(UIFont*)font{
    CGRect screen = [UIScreen mainScreen].bounds;
    CGFloat maxWidth = screen.size.width;
    CGSize maxSize = CGSizeMake(maxWidth, CGFLOAT_MAX);
    
    CGSize textSize = CGSizeZero;
    // iOS7以后使用boundingRectWithSize,之前使用sizeWithFont
    if ([text respondsToSelector:@selector(boundingRectWithSize:options:attributes:context:)]) {
        // 多行必需使用NSStringDrawingUsesLineFragmentOrigin
        NSStringDrawingOptions opts = NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading;
        NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
        [style setLineBreakMode:NSLineBreakByCharWrapping];
        NSDictionary *attributes = @{ NSFontAttributeName : font, NSParagraphStyleAttributeName : style };
        CGRect rect = [text boundingRectWithSize:maxSize
                                         options:opts
                                      attributes:attributes
                                         context:nil];
        textSize = rect.size;
    } else{
        textSize = [text sizeWithFont:font constrainedToSize:maxSize lineBreakMode:NSLineBreakByCharWrapping];
    }
    return textSize;
}

@end

使用时 导入头文件 #import "UIButton MutableTitle.h"

代码语言:javascript复制
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 100, 40)];
    button.center = self.view.center;
    button.backgroundColor = [UIColor redColor];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [button setMutableTitleWithString:@"qwertyudfghjkl;iadsdajshdashdasdlshdertyudiertyudfghjkl;io" textFont:[UIFont systemFontOfSize:14] forState:UIControlStateNormal];
    [self.view addSubview:button];

Simulator Screen Shot 2016年8月25日 下午7.26.54.png

0 人点赞