Swift - 如何为 UISearchBar 提供阴影但*不*它的取消按钮?

Swift - How to give shadow to UISearchBar but *not* its cancel button?

我有一个应用了投影的搜索栏,如您所见here,取消按钮也投射了自己的阴影。我希望阴影仅限于搜索文本框。这是我的开头:

    let searchBar = UISearchBar()
    searchBar.placeholder = "KAT Milkshake"
    searchBar.backgroundImage = UIImage()
    searchBar.barTintColor = UIColor.white
    searchBar.compatibleSearchTextField.leftView?.tintColor = UIColor.gray
    searchBar.compatibleSearchTextField.backgroundColor = UIColor.white

    searchBar.layer.shadowColor = UIColor.black.cgColor
    searchBar.layer.shadowOpacity = 0.25
    searchBar.layer.shadowOffset = CGSize(width: 2, height: 2)
    searchBar.layer.shadowRadius = 5

我尝试过的:

  1. 我尝试通过 UIBarButtonItem.appearance(whenContainedInInstancesOf: [UISearchBar.self]) 更改取消按钮的外观,但事实证明该对象的阴影是一个单独的阴影。在我通过修改外观阴影属性应用另一个阴影后,请注意微妙的 difference around the letters。

  2. 为按钮提供白色图像背景无效,我通过访问 searchBar.value(forKey: "cancelButton") as! UIButton 做到了这一点。应用了阴影 around the whole image,看起来更糟。

  3. 不幸的是,调整搜索栏图层的边界也没有用( searchBar.layer.frame = CGRect(x: searchBar.frame.minX, y: searchBar.frame.minY, width: searchBar.frame.width - cancelButton.frame.width, height: searchBar.frame.height))。 我给搜索栏层一个边框来观察这个,取消按钮阴影 persists.

  4. 我也尝试取消取消按钮与超级视图的链接,但只能让它完全消失。

有什么办法解决这个问题吗?我在 Swift 5 和 iOS 14.

正如 ibrahimyilmaz 所建议的那样,将阴影添加到 UITextField 而不是 UISearchBar 就完成了工作。只需修改我的高度和布局锚点约束来处理裁剪。

我关注 this example 用户 Joshpy 以访问文本字段。对于 iOS >= 13,制作阴影很简单:

    searchBar.searchTextField.layer.shadowColor = UIColor.black.cgColor
    searchBar.searchTextField.layer.shadowOpacity = 0.25
    searchBar.searchTextField.layer.shadowOffset = CGSize(width: 2, height: 2)
    searchBar.searchTextField.layer.shadowRadius = 5