cac*_*tus 38 cocoa-touch background-color uibarbuttonitem uisearchbar ios
当我将UISearchBar放入Interface Builder中的视图中,并将其样式更改为Black Opaque时,取消按钮保持不合适的蓝色/灰色并且不会变为黑色.
如何将取消按钮设为黑色?
编辑:它确实像这样工作:
// Assume a UISearchBar searchBar.
NSArray *subviews = [searchBar subviews];
// The index depends on how you configure the searchBar.
UIButton *cancelButton = [subviews objectAtIndex:3];
// Set the style to "normal" style.
[cancelButton setStyle:0];
Run Code Online (Sandbox Code Playgroud)
但该setStyle:
方法来自私有框架,因此在向Apple提交应用程序时可能会出现问题.
Hos*_*eeb 113
我用过这样的东西并和我一起工作:
[[UIBarButtonItem appearanceWhenContainedIn: [UISearchBar class], nil] setTintColor:[UIColor blackColor]];
Run Code Online (Sandbox Code Playgroud)
它将取消按钮颜色更改为黑色.
iOS 9.0 更新,该方法appearanceWhenContainedIn
已弃用,请appearanceWhenContainedInInstancesOfClasses
改用:
[[UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[UISearchBar class]]] setTintColor:[UIColor blackColor]];
Run Code Online (Sandbox Code Playgroud)
在Swift 3中:
UIBarButtonItem.appearance(whenContainedInInstancesOf:[UISearchBar.self]).tintColor = UIColor.black
Run Code Online (Sandbox Code Playgroud)
小智 33
您的解决方案的问题是代码假设objectAtIndex:3是取消按钮.这不仅会生成编译器警告,而且如果您以编程方式显示"取消"按钮(例如使用[searchBar setShowsCancelButton:YES]
,则可能会导致应用程序崩溃).
一个更简单的解决方案是使用以下方法在ViewDidLoad()中设置整个搜索栏的样式:
searchBar.tintColor = [UIColor colorWithWhite:0.3 alpha:1.0];
Run Code Online (Sandbox Code Playgroud)
这将覆盖Interface Builder中设置的样式但是也会将"取消"按钮的颜色更改为与整个栏相同的颜色(尽管它不允许您单独设置"取消"按钮的样式.
Try this and see: (I tested below code with Swift 4.1 - Xcode 9.3-beta4)
@IBOutlet weak var sbSearchBar: UISearchBar!
sbSearchBar.tintColor = UIColor.red
sbSearchBar.showsCancelButton = true
sbSearchBar.barTintColor = UIColor.blue
sbSearchBar.tintColor = UIColor.red
if let buttonItem = sbSearchBar.subviews.first?.subviews.last as? UIButton {
buttonItem.setTitleColor(UIColor.yellow, for: .normal)
}
Run Code Online (Sandbox Code Playgroud)
对于 iOS 10:
UISearchBar.appearance().tintColor = UIColor.red //cancel button color
UISearchBar.appearance().barTintColor = UIColor.blue //background button color
Run Code Online (Sandbox Code Playgroud)
在Swift 4.2中
let appearance = UIBarButtonItem.appearance(whenContainedInInstancesOf: [UISearchBar.self])
appearance.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor(named: "goldColor")!], for: .normal)
Run Code Online (Sandbox Code Playgroud)
这对我有用。谢谢@Tim Semple
归档时间: |
|
查看次数: |
28735 次 |
最近记录: |