我想将按钮上的文本颜色更改为加载时的蓝色。我还只需要按钮文本的前9个字母(用户名的长度)为蓝色,而不是全部文本即可。我该怎么做呢?
例:
上图显示“@LisaLisa正在关注您”。这是按钮文本。如何使“@LisaLisa”变为蓝色,而“正在关注您”则保持黑色?
最佳答案
UILabel * myLabel = [[UILabel alloc] init];//used for whole string
myLabel.numberOfLines = 0;
NSString * myUserName = @"@LisaLisa";//used for userName
//add button on UserName
UIButton * muButton = [[UIButton alloc] init];
myLabel.text = [NSString stringWithFormat:@"%@", myUserName];
myLabel = [self setDynamicLableFrame:myLabel fontSize:fontSize Width:width];
//Here width is your Label's Width. Because we have to make sure that our, our label's width is not greater than our device's width and fontSize is label's fontSize
muButton.frame = myLabel.frame;
myLabel.text = [NSString stringWithFormat:@"%@ is following you", myUserName];
myLabel = [self setDynamicLableFrame:myLabel fontSize:fontSize Width:width];//used for making dynamic height of label
//For changing color of UserName
NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithAttributedString: myLabel.attributedText];
[text addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(0, myUserName.length)];
[myLabel setAttributedText: text];
以下方法用于制作标签的动态高度和宽度。因为我们只需要在UserName(“LisaLisa”)上设置Button的框架。
//for setting the dynamic height of labels
-(UILabel *)setDynamicLableFrame:(UILabel*)myLabel fontSize:(float)size Width:(float)Width
{
CGSize possibleSize = [myLabel.text sizeWithFont:[UIFont fontWithName:REGULER_FONT size:size] constrainedToSize:CGSizeMake(300, 9999) lineBreakMode:NSLineBreakByWordWrapping];
CGRect newFrame = myLabel.frame;
newFrame.size.height = possibleSize.height;
if (possibleSize.width < Width) {
newFrame.size.width = possibleSize.width;
}else{
newFrame.size.width = Width;
}
myLabel.frame = newFrame;
return myLabel;
}
希望,这就是您想要的。如有任何疑问,请联系我。
关于ios - 在iOS中更改按钮文本的颜色(objective-c),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33813817/