iOS - UILabel添加圖片之富文本的簡單應用


 

//創建富文本
    NSMutableAttributedString *attri = [[NSMutableAttributedString alloc] initWithString:@" -積分商城-熱門商品-優惠券,后續會陸續打通東方明珠塔等各類上海文化消費優惠券。"];
    //NSTextAttachment可以將要插入的圖片作為特殊字符處理
    NSTextAttachment *attch = [[NSTextAttachment alloc] init];
    //定義圖片內容及位置和大小
    attch.image = [UIImage imageNamed:@"home_profile_icon"];
    attch.bounds = CGRectMake(0, 0, 15, 15);
    //創建帶有圖片的富文本
    NSAttributedString *string = [NSAttributedString attributedStringWithAttachment:attch];
    
    //將圖片放在最后一位
    //[attri appendAttributedString:string];
    //將圖片放在第一位
    [attri insertAttributedString:string atIndex:0];
    //用label的attributedText屬性來使用富文本
    _imgLabel.attributedText = attri;
    
    //若想對圖片添加點擊事件,現在的想法是在label上添加一個透明按鈕,位置大小跟圖片的相同
    _imgLabel.userInteractionEnabled = YES;
    UIButton *clearBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    clearBtn.frame = CGRectMake(0, 12, attch.bounds.size.width, attch.bounds.size.height+3);
    clearBtn.backgroundColor = [UIColor clearColor];
    [clearBtn addTarget:self action:@selector(alertSth) forControlEvents:UIControlEventTouchUpInside];
    [_imgLabel addSubview:clearBtn];

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM