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


若想對UILabel添加圖片,那么就需要使用NSMutableAttributedString來定義
先定義一個普通的label

UILabel *lab = [[UILabel alloc]initWithFrame:CGRectMake(10, 100, self.view.frame.size.width-10, 100)]; lab.numberOfLines = 0; [self.view addSubview:lab];

然后對其定義

//創建富文本
NSMutableAttributedString *attri = [[NSMutableAttributedString alloc] initWithString:@" 我納斯達克市場部撒草卡死你查看售樓處內 按時打算打算的撒打算離開的驕傲是是大神快了解到撒開了就對啦可視對講盧卡斯的卡洛斯的驕傲"]; //NSTextAttachment可以將要插入的圖片作為特殊字符處理
NSTextAttachment *attch = [[NSTextAttachment alloc] init]; //定義圖片內容及位置和大小
attch.image = [UIImage imageNamed:@"tab_suning"]; attch.bounds = CGRectMake(0, 0, 61, 14); //創建帶有圖片的富文本
NSAttributedString *string = [NSAttributedString attributedStringWithAttachment:attch];
//將圖片放在最后一位 //[attri appendAttributedString:string]; //將圖片放在第一位
[attri insertAttributedString:string atIndex:0]; //用label的attributedText屬性來使用富文本
lab.attributedText = attri;

然后效果如下

若想對圖片添加點擊事件,現在的想法是在label上添加一個透明按鈕,位置大小跟圖片的相同

lab.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]; [lab addSubview:clearBtn];

效果如下


免責聲明!

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



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