在iOS中设置两种不同颜色的button标题
我想用两种颜色在Button上设置标题。
它可能与下面给出的图像相同吗?
任何帮助将不胜感激。
提前致谢。
这是你需要的
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom]; btn.frame = CGRectMake(5,10,300,20); [self.view addSubview:btn]; NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"100 Photos"]]; [attrStr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0, 3)]; [btn setAttributedTitle:attrStr forState:UIControlStateNormal];
在storyBoard:按照ScreenShot。
以编程方式:已经有许多答案职位在这里为属性文本和如果你想把UIButton BackgroundImage 设置button背景图像iPhone编程
尝试这个
NSMutableAttributedString *mutableString = [[NSMutableAttributedString alloc] initWithString:@"ThisIsAttributed"]; [mutableString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0,4)]; [mutableString addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(5,2)]; [button setAttributedTitle:mutableString forState:UIControlStateNormal];
对于迅捷3:
let button = UIButton() let mainTitle = "200" let subtitle = "Members" let attrText1 = NSMutableAttributedString(string: mainTitle) attrText1.addAttribute(NSFontAttributeName, value: 15, range: NSMakeRange(0, attrText1.length)) attrText1.addAttribute(NSForegroundColorAttributeName, value: UIColor.black, range: NSMakeRange(0, attrText1.length)) let attrText2 = NSMutableAttributedString(string: subtitle) attrText2.addAttribute(NSFontAttributeName, value: 15, range: NSMakeRange(0, attrText2.length)) attrText2.addAttribute(NSForegroundColorAttributeName, value: UIColor.yellow, range: NSMakeRange(0, attrText2.length)) let attributedText = NSMutableAttributedString() attributedText.append(attrText1) attributedText.append(attrText2) //Center align let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.alignment = .center attributedText.addAttribute(NSParagraphStyleAttributeName, value: paragraphStyle, range: NSMakeRange(0,attributedText.length)) button.setAttributedTitle(attributedText, for: .normal)
[button setAttributedTitle:someAttributedText forState:UIControlStateNormal];
你可以使用5.0以下的ios和当前ios版本的NSMutableAttributedString
。