Я знаю, что в JavaScript существует функция, которая меняет контраст в зависимости от того, какой цвет выбран в данный момент:
function getHigherContrast(r, g, b) {
const yiq = ((r * 299) + (g * 587) + (b * 114)) / 1000;
return (yiq >= 128) ? '#000000' : '#FFFFFF';
}
Как я могу переписать эту функцию в Swift-Code, чтобы контраст изменилсякаждый раз, когда пользователь выбирает другой цвет:
override func viewDidLoad() {
super.viewDidLoad()
self.view.addSubview(colorPicker)
colorPicker.translatesAutoresizingMaskIntoConstraints = false
colorPicker.trailingAnchor.constraint(equalTo: self.view.layoutMarginsGuide.trailingAnchor).isActive = true
colorPicker.leadingAnchor.constraint(equalTo: self.view.layoutMarginsGuide.leadingAnchor).isActive = true
colorPicker.topAnchor.constraint(equalTo: self.view.layoutMarginsGuide.topAnchor).isActive = true
colorPicker.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action:#selector(handleDone(sender:)))
colors.append((colorTitle: "rot", color: UIColor.red))
colors.append((colorTitle: "gelb", color: UIColor.yellow))
colors.append((colorTitle: "grün", UIColor.green))
colors.append((colorTitle: "schwarz", UIColor.black))
colorPicker.delegate = self
colorPicker.dataSource = self
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return colors.count
}
func pickerView(_ pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? {
return NSAttributedString(string: colors[row].colorTitle, attributes: [NSAttributedStringKey.foregroundColor: colors[row].color])
}
@objc func handleDone(sender: AnyObject?) {
if let d = delegate {
d.colorPicked(color: colors[colorPicker.selectedRow(inComponent: 0)].color)
}
dismiss(animated: true)
}
Здесь - полный исходный код класса.