OC 自定义导航栏返回按钮宽度自适应

+(UIBarButtonItem *)backButtonWithTitle:(NSString *)title titleColor:(UIColor *)color imageName:(NSString *)imageName target:(id)target action:(SEL)action{
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
    
    [button setTitleColor:color forState:UIControlStateNormal];
    [button setTitle:title forState:UIControlStateNormal];
    button.titleLabel.font = [UIFont boldSystemFontOfSize:15];
    
    [button setImage:[[UIImage imageNamed:imageName] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
    [button setImage:[[UIImage imageNamed:[NSString stringWithFormat:@"%@_selected", imageName]] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateSelected];
    
    button.imageEdgeInsets = UIEdgeInsetsMake(0, -5, 0, 0);
    
    [button addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
    
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineBreakMode = NSLineBreakByTruncatingTail;//省略方式 ...在后面 
    
    NSDictionary *attributes = @{
                                 NSParagraphStyleAttributeName : paragraphStyle,
                                 };
    button.titleLabel.attributedText = [[NSAttributedString alloc] initWithString:title attributes: attributes];
    
    [button sizeToFit];
    
    //100是你想限制的最大宽度
    if (button.width > 100)
    {
        button.width = 100;
    }
    
    return [[UIBarButtonItem alloc]initWithCustomView:button];
}

 

posted @ 2016-05-16 10:59  Joe.Z  阅读(358)  评论(0)    收藏  举报