如何将UITableView中的文本更改为两种不同的颜色?
let highest = (history[indexPath.row].highest!) //Red color
let lowest = (history[indexPath.row].lowest!) //Green color
cell.detailTextLabel?.text = "$\(highest)/$\(lowest)"
return cell
谢谢!
答案 0 :(得分:0)
您的输出将如下所示:
您可以像这样简单地完成
//your constants
let highest = (history[indexPath.row].highest!) //Red color
let lowest = (history[indexPath.row].lowest!) //Green color
// a string combining them
let concatOfHighestLowest = "$\(highest)/$\(lowest)"
//the attributed mutable string .
let finalString = NSMutableAttributedString(string: concatOfHighestLowest)
// 1 in NSRange Locations stands for the "$" symbol.
finalString.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.red, range: NSRange(location:1,length:highest.count))
// highest.count + 3 in NSRange stands for the "$ , /" symbols and after the highest value.
finalString.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.green, range: NSRange(location:highest.count + 3,length:lowest.count))
cell.detailTextLabel?.attributedText = finalString
return cell
答案 1 :(得分:0)
使用NSMutableAttributedString
let myString = NSMutableAttributedString(string: "$\(highest)/$\(lowest)" )
let heighestRange = myString.mutableString.range(of: highest)
myString.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.red, range: heighestRange)
let lowestRange = myString.mutableString.range(of: lowest)
myString.addAttribute(.foregroundColor, value: UIColor.green, range: lowestRange)
答案 2 :(得分:0)
import axios from 'axios';
import ResetPassword from "./components/SignUp/ResetPwd";
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
loading: false,
expiredToken : null
};
this.checkToken = this.checkToken.bind(this);
}
checkToken(token) {
console.log('checkToken');
this.setState({loading: true}, () => {
let url = `${this.state.config.apiURL}/checkToken`;
let method = 'post';
axios.request({
url: url,
method: method,
data: {
token: token
}
}).then(results => {
if (results.data === null) {
this.setState({
loading: false,
expiredToken: true
})
} else {
console.log(results.data);
this.setState({
loading: false,
expiredToken: false
});
}
})
})
}
render() {
const ResetPwd = (props) => {
return (
<div>
<ResetPassword appState={this.state} {...props} checkToken={this.checkToken}/>
</div>
)
};
}
}
通过使用上述扩展名,您可以为标签设置文本颜色,如下所示
extension NSMutableAttributedString {
func setColor(color: UIColor, forText stringValue: String) {
let range: NSRange = self.mutableString.range(of: stringValue, options: .caseInsensitive)
self.addAttribute(NSAttributedStringKey.foregroundColor, value: color, range: range)
}
}
输出将如下所示