我想知道在iOS中改变UITextField(和UITextView如果答案相同)中的光标/插入符号的颜色。我看到过OSX开发的答案,但没有iOS的答案。

这可能吗?


当前回答

如果UITextField来自UISearchBar,那么首先从searchBar获得textField,然后应用tintColor属性:

let textFieldInsideSearchBar = searchBar.value(forKey: "searchField") as? UITextField
textFieldInsideSearchBar?.tintColor = UIColor.lightGray

其他回答

这在swift中很管用:

UITextField.tintColor = UIColor.blackColor()

你也可以在storyboard中设置:https://stackoverflow.com/a/18759577/3075340

如果UITextField来自UISearchBar,那么首先从searchBar获得textField,然后应用tintColor属性:

let textFieldInsideSearchBar = searchBar.value(forKey: "searchField") as? UITextField
textFieldInsideSearchBar?.tintColor = UIColor.lightGray

为UITextField和UITextView设置tintColor的工作方式不同。 虽然对于UITextField,你不需要在更新tintColor后调用额外的代码来改变光标的颜色,但对于UITextView,你需要。

所以在设置tintColor为UITextView(这并不重要在IB或在代码),你需要调用textView.tintColorDidChange(),以应用它(实际上它将通过文本视图的配置下到它的子视图层次结构)。

在iOS7中,你可以简单地改变textField的tintColor

一个更通用的方法是设置UIView的外观的tintColor。

UIColor *myColor = [UIColor purpleColor];
[[UIView appearance] setTintColor:myColor];

如果您使用许多默认UI元素,这是有意义的。