OC實(shí)現(xiàn)簡單的圖文混排

效果圖
image
- (void)showCity:(NSString *)cityname  
{  
    //實(shí)現(xiàn)富文本  
    NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:cityname attributes:nil];  
    //進(jìn)行圖文混排  
    NSTextAttachment *textAttachment = [[NSTextAttachment alloc] initWithData:nil ofType:nil];  
    textAttachment.image = [UIImage imageNamed:@"f_flagdown02@2x"];  
    textAttachment.bounds =CGRectMake(0,0, 11,8);  
    NSAttributedString * textAttachmentString = [NSAttributedString attributedStringWithAttachment:textAttachment];  
    //判斷選擇的城市名稱長度是否大于5個(gè)字符的長度,如果大于五個(gè)字符就取前四個(gè)字符,然后再在最后添加一個(gè)圖標(biāo)  
    if (string.length >=5) {  
        //去前四個(gè)字符  
        NSAttributedString *str = [string attributedSubstringFromRange:NSMakeRange(0,4)];  
        //將NSAttributedString類型轉(zhuǎn)換成NSString類型  
        NSString *cityString = [str string];  
        string = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@..",cityString] attributes:nil];  
    }  
  
    //在城市名稱后插入圖片  
    [string insertAttributedString:textAttachmentString atIndex:string.length];  
    //自定義按鈕  
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];  
    btn.frame =CGRectMake(0,0, 70,30);  
    [btn addTarget:self action:@selector(navBtnCLick)forControlEvents:UIControlEventTouchUpInside];  
    UILabel *lbText = [[UILabel alloc] initWithFrame:CGRectMake(0,0, btn.frame.size.width+10, btn.frame.size.height)];  
    lbText.attributedText = string;  
    lbText.textColor = [UIColorwhite Color];  
    lbText.font = [UIFont systemFontOfSize:13];  
    [btn addSubview:lbText];  
    btn.backgroundColor = [UIColor clearColor];  
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:btn];  
}  
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容