ios - 在iOS中更改按钮文本的颜色(objective-c)

标签 ios objective-c button colors

我想将按钮上的文本颜色更改为加载时的蓝色。我还只需要按钮文本的前9个字母(用户名的长度)为蓝色,而不是全部文本即可。我该怎么做呢?

例:
enter image description here

上图显示“@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/

相关文章:

ios - UIMenuController响应非常慢

ios - 在 Objective-c 上使用静态 Swift 方法时出现 "No known class method for selector"

ios - 如何使用复合 NSPredicate?

android - 在 AsyncTask 期间禁用按钮

ios - 将通用应用程序转换为 iPad 应用程序

ios - APNS 中重复的通知标识符安全吗

ios - 拼贴应用程序的自定义 UIView

C++ 二进制作用域解析运算符和类

ios - 当创建带有框架的惰性按钮时,这是在左上角创建的,为什么会发生这种情况?

html - 使用 google API 将 google+ 登录按钮实现到本地主机