HWSearchBar.m 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. //
  2. // HWSearchBar.m
  3. // 双子星云手机
  4. //
  5. // Created by 余衡武 on 2022/3/9.
  6. //
  7. #import "HWSearchBar.h"
  8. @interface HWSearchBar () <UITextFieldDelegate>
  9. @end
  10. @implementation HWSearchBar
  11. + (instancetype)shareInstance {
  12. return [[NSBundle mainBundle] loadNibNamed:@"HWSearchBar" owner:self options:nil].firstObject;
  13. }
  14. - (void)awakeFromNib {
  15. [super awakeFromNib];
  16. [self drawView];
  17. }
  18. - (void)drawView {
  19. self.bgView.backgroundColor = HWFFFFFF10Color;
  20. self.bgView.layer.cornerRadius = 10;
  21. self.bgView.layer.masksToBounds = YES;
  22. self.searchImageView.hidden = self.textField.text.length != 0;
  23. self.searchPlaceHolder.hidden = self.textField.text.length != 0;
  24. [self.searchPlaceHolder setText:NSLocalizedString(@"Search_or_type_in_the_URL",nil)];
  25. [self.textField addObserver:self forKeyPath:@"text" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];
  26. self.textField.clearButtonMode = UITextFieldViewModeWhileEditing;
  27. self.textField.returnKeyType = UIReturnKeySearch;
  28. [self.textField addTarget:self action:@selector(textDidChange:) forControlEvents:UIControlEventEditingChanged];
  29. self.textField.delegate = self;
  30. self.textField.textColor = HWFFFFFFColor;
  31. }
  32. #pragma mark KVO
  33. -(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
  34. if ([keyPath isEqualToString:@"text"]) {
  35. self.searchImageView.hidden = self.textField.text.length != 0;
  36. self.searchPlaceHolder.hidden = self.textField.text.length != 0;
  37. if (self.textField.text.length == 0) {
  38. self.textField.placeholder = NSLocalizedString(@"Search_or_type_in_the_URL",nil);
  39. }
  40. }
  41. }
  42. #pragma mark UITextFieldDelegate
  43. - (void)textFieldDidBeginEditing:(UITextField *)textField {
  44. self.searchImageView.hidden = YES;
  45. self.searchPlaceHolder.hidden = YES;
  46. }
  47. - (void)textFieldDidEndEditing:(UITextField *)textField {
  48. // HLog(@"搜索或加载网页");
  49. self.searchImageView.hidden = textField.text.length != 0;
  50. self.searchPlaceHolder.hidden = textField.text.length != 0;
  51. }
  52. - (BOOL)textFieldShouldReturn:(UITextField *)textField {
  53. // HLog(@"搜索");
  54. [self.textField endEditing:YES];
  55. if ([_delegate respondsToSelector:@selector(searchBarWithText:)]) {
  56. [_delegate searchBarWithText:textField.text];
  57. }
  58. return YES;
  59. }
  60. - (void)textDidChange:(UITextField*)textField{
  61. if ([_delegate respondsToSelector:@selector(searchBarChangeText:)]) {
  62. [_delegate searchBarChangeText:textField.text];
  63. }
  64. }
  65. @end