代码之家  ›  专栏  ›  技术社区  ›  Nathan Kellert

UISearchBar不会删除UISearchBarBackground

  •  1
  • Nathan Kellert  · 技术社区  · 7 年前

    我已经尽了一切努力让它发挥作用。我这样设置了一个自定义类。

    override func layoutSubviews() {
        super.layoutSubviews()
        clearBackgroundColor() // function in the question
    
    }
    
    private func clearBackgroundColor() {
        guard let UISearchBarBackground: AnyClass = NSClassFromString("UISearchBarBackground") else { return }
    
        for view in self.subviews {
            for subview in view.subviews {
                if subview.isKind(of: UISearchBarBackground) {
                    subview.alpha = 0
                }
            }
        }
    }
    

    这是在iOS 10和am上使用的故事板。任何帮助都将不胜感激。

    2 回复  |  直到 7 年前
        1
  •  1
  •   meaning-matters    7 年前

    不久前,我不得不在一个客户的应用程序中这样做。以下是对我有效的方法:

    我有一个 UISearchBar

    @property (nonatomic, strong) UITextField* textField;
    

    我打了以下电话 init :

        self.textField                 = [self findViewOfClass:[UITextField class] inView:self];
    
        self.translucent               = NO;   
        self.barTintColor              = ...;
        self.textField.backgroundColor = ...;
    
    - (id)findViewOfClass:(Class)class inView:(UIView*)view
    {
        if ([view isKindOfClass:class])
        {
            return view;
        }
        else
        {
            for (UIView* subview in view.subviews)
            {
                id foundView = [self findViewOfClass:class inView:subview];
    
                if (foundView != nil)
                {
                    return foundView;
                }
            }
        }
    
        return nil;
    }
    

    关键是找到 UITextField translucent 是真正需要的;易于尝试。

    应该是这样。如果这对你有效,请告诉我。

    我只有Obj-C代码,但这很容易转换。

        2
  •  1
  •   Nathan Kellert    7 年前

    searchBar.setSearchFieldBackgroundImage(UIImage(), for: .normal)
    

    需要注意的是,这并不是解决此问题的唯一方法。然而,我使用它是因为它不需要循环,并且因为图像是空的,所以添加的附加视图永远不会与其他方法产生相同的最终结果。

    需要注意的是,这可能只适用于iOS 9+。因此,你的milage可能会有所不同。我使用iOS 10进行了测试,部署目标为9.3。