0

For example. I got a UISearchBar which I wanted to make a totally same copy.

I think it could be done by implementing the copy(with:) (copyWithZone:) of NSObject and then call the copy().

But what I don't know is what to do inside the copyWithZone in Swift.

I just need a copy of the UISearchController's UISearchBar.
Let's say we have a topic about how to copy an instance.
How to make that happen?

Ashley Mills
  • 50,474
  • 16
  • 129
  • 160
JsW
  • 1,682
  • 3
  • 22
  • 34

1 Answers1

1

UISearchBar cannot be copied as it doesn't adopt NSCopying.

You have to create a new instance of UISearchBar and apply the customizations, for this you can also create an struct that holds the settings, like so:

struct SearchBarConfig {
    var placeholder: String?
    var isTranslucent: Bool

    // Display Attributes
    var barStyle: UIBarStyle
    var barTintColor: UIColor?
    var searchBarStyle: UISearchBarStyle
    var tintColor: UIColor!

    init(isTranslucent: Bool, barStyle: UIBarStyle, searchBarStyle: UISearchBarStyle) {
        self.isTranslucent = isTranslucent
        self.barStyle = barStyle
        self.searchBarStyle = searchBarStyle
    }
}

let existingSearchBar = UISearchBar()
var existingStatusBarConfig = SearchBarConfig(
    isTranslucent: existingSearchBar.isTranslucent,
    barStyle: existingSearchBar.barStyle,
    searchBarStyle: existingSearchBar.searchBarStyle)

Now if you have above implemented, you can just create a new searchBar and apply the attributes.

AamirR
  • 11,672
  • 4
  • 59
  • 73
  • So there is no convenient way? – JsW Aug 11 '18 at 08:05
  • 4
    UISearchbar does inherit from NSObject. It doesnt adopt NSCopying though. – Sulthan Aug 11 '18 at 08:06
  • @JsW "Why UIView cannot adopt NSCopying"?, refer to this post https://stackoverflow.com/a/1552137, I like how Frank explained in this answer https://stackoverflow.com/a/1556426/1244597 – AamirR Aug 11 '18 at 08:14
  • 1
    `UIView` inherit from `UIResponder` which inherit from `NSObject` – JsW Aug 11 '18 at 08:30
  • @JsW Although UIView does inherit from NSObject (as almost all classes in Objective-C) do, that does not mean that it adopts the NSCopying protocol. – Abizern Aug 11 '18 at 11:31
  • @Abizern yeah, I realized it now :p – JsW Aug 11 '18 at 23:38