欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

iOS如何将字符串中特定后的字变成红色

程序员文章站 2023-12-21 13:24:10
一,效果图。 二,代码。 viewcontroller.m - (void)viewdidload { [super viewdidload];...

一,效果图。

iOS如何将字符串中特定后的字变成红色

二,代码。

viewcontroller.m

- (void)viewdidload {
  [super viewdidload];
  // do any additional setup after loading the view, typically from a nib.
  uilabel *testlabel=[[uilabel alloc]initwithframe:cgrectmake(10, 100, 100, 50)];
  testlabel.text=@"1234567890";
  testlabel.backgroundcolor=[uicolor orangecolor];
  [self.view addsubview:testlabel];
  [self redxingwithlabel:testlabel atindex:2];
}
//将字符串特定的1个字变成红色
- (void)redxingwithlabel:(uilabel *)templabel atindex:(nsinteger)tempindex {
  nsmutableattributedstring * tempstring = [[nsmutableattributedstring alloc] initwithstring: templabel.text];
  [tempstring addattribute:nsforegroundcolorattributename value:[uicolor redcolor] range:nsmakerange(tempindex, 1)];
  templabel.attributedtext = tempstring;
}

以上所述是小编给大家介绍的ios如何将字符串中特定后的字变成红色,希望对大家有所帮助

上一篇:

下一篇: