2017-09-05 81 views
2

是否可以爲NSTextField對象設置選定文本的高亮顏色?默認情況下,它將使用用戶在其系統偏好設置中設置的顏色,但我想將其更改爲深灰色並帶有白色文本以與我的應用程序的樣式相匹配。爲NSTextField設置選定文本的高亮顏色

回答

-1

請檢查下面的代碼:

func textFieldDidSelected(_ textField: UITextField) { 
    if let selectedRange = textField.selectedTextRange { 
     if !(selectedRange.isEmpty) { 
      let location = textField.offset(from: textField.beginningOfDocument, to: selectedRange.start) 
      let length = textField.offset(from: selectedRange.start, to: selectedRange.end) 

      let string:NSMutableAttributedString = NSMutableAttributedString(string: textField.text!) 

      string.addAttribute(NSForegroundColorAttributeName, value: UIColor.white, range: NSRange(location: location, length: length)) 
      string.addAttribute(NSBackgroundColorAttributeName, value: UIColor.black, range: NSRange(location: location, length: length)) 
      textField.attributedText = string 
     } 
    } 
} 
+1

謝謝,但這個答案是對的UITextField(IOS),我構建使用的NSTextField MacOS的應用程序。 – generator