GithubHelp home page GithubHelp logo

blackjacx / shsearchbar Goto Github PK

View Code? Open in Web Editor NEW
253.0 7.0 35.0 2.11 MB

The search bar that doesn't suck.

License: MIT License

Swift 98.94% Objective-C 0.60% Ruby 0.46%
uisearchbar carthage carthage-support swiftpackagemanager spm cocoapods ios xcode apple search

shsearchbar's Introduction

Twitter Follow Twitter Follow Version Swift Versions Platforms Codebeat License Donate

SHSearchBar

The clean and shiny search bar that does what UISearchBar does only with dirty hacks. This view is designed to tackle the customization limits of UISearchBar. The difference here is that this class does not inherit UISearchBar but composes a new UIView object by using a UITextField that is much easier to use. These are the limits of the UISearchBar:

  • no clean way to left align the placeholder
  • the cancel button is hard to tailor to your needs
  • generally the appearance is not customizable (e.g. the font of the text)
  • there are some strange behaviors when you set a custom background image

Since I use a UITextField these restrictions do not apply.

Installation

In Xcode open your target list and select your project. Click the tab Swift Packages and there the small + icon. Enter the URL of this repository, select the version you want to install - usually the preset is okay - and confirm.

Since SHSearchBar uses localized resources I dropped CocoaPods support in favor of SPM from version 2.0.0. Please integrate the package via SPM (see above).

Carthage

Since SHSearchBar uses localized resources I dropped Carthage support in favor of SPM from version 2.0.0. Please integrate the package via SPM (see above).

Examples

The repo includes an example project. It shows shows different use cases of the search bar. To run it, just open and run ./Example/SHSearchBarExample.xcodeproj. The following images show some use cases:

You can show a custom placeholder like for normal text fields:
Placeholder

And you can even type text into that searchbar:
Text

Wow there are customizable accessory views too:
Accesssory Icon

Easily customize text and cancel button as you want:
Customizable text and ancel button

You can customize each corner radius of the text field so that layouts like this become an ease:
Corner Radius Customization

The inner text field supports the new iOS 10 'textContentMode':
(Re-uses the address searched in Apple Maps before)
UITextContentMode Support

You can use the search bar inside a UINavigationBar:
UINavigationBar Support

Code Documentation

The code documentation is generated and hosted by Swift Package Index (powered by DocC)

Release

To release this Swift package the following steps have to be taken:

  • Create a new branch release-x.y.z
  • Run bash <(curl -H -s https://raw.githubusercontent.com/Blackjacx/Scripts/master/frameworks/bootstrap.sh) to update to the latest shared development files
  • Run bundle update to update all Ruby gems
  • Commit all changes, make a PR and merge it to develop
  • Run bundle exec fastlane release framework:"SHSearchBar" version:"x.y.z" to release the new version
  • Post the following on Twitter
SHSearchBar release x.y.z ๐ŸŽ‰

โ–ธ ๐Ÿš€  SHSearchBar (x.y.z) successfully published
โ–ธ ๐Ÿ“…  September 2nd
โ–ธ ๐ŸŒŽ  https://swiftpackageindex.com/Blackjacx/SHSearchBar
โ–ธ ๐ŸŒŽ  https://github.com/Blackjacx/SHSearchBar/releases/latest
โ–ธ ๐Ÿ‘  Tell your friends!

#spm #search #ios #apple #xcode #uisearchbar #swiftpackagemanager

Contribution

  • If you found a bug, please open an issue.
  • If you have a feature request, please open an issue.
  • If you want to contribute, please submit a pull request.

Author

Stefan Herold โ€ข ๐Ÿฆ @Blackjacxxx

Contributors

Thanks to all of you who are part of this:

License

SHSearchBar is available under the MIT license. See the LICENSE file for more info.

shsearchbar's People

Contributors

blackjacx avatar csr avatar finestructure avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

shsearchbar's Issues

[UI] Transfer active/inactive state to the left and right views of the UITextField

Consider setting an inactive version of the left and right views. To implement the active/inactive state of these views, try the following when the active/inactive state of the searchbar changes (in that order):

  • enable/disable the views (possible if they are descendants of UIControl)
  • change the tint color of the views (possible if they are descendants of UIView)

Hide the UITextField inside the SHSearchBar

It is important to hide the text field behind a public API. This enables to switch technologies behind the SHSearchBar without affecting users of the framework.

Here it is important to offer all the functionality in the public API like the normal UISearchBar does plus advantages a UITextField has. These are:

UITextField Features

  • [set/get] defaultTextAttributes

  • [set/get] typingAttributes
    (the above 2 are better than setting the attributedText directly since we are able to access the attributes and thus are more flexible)

  • [set/get] attributedPlaceholder

  • [set/get] leftView

  • [set/get] rightView

  • [set/get] tintColor (directly maps to the cursor color)

  • [set/get] text

  • [set/get] isEnabled

  • [call] resignFirstResponder()

SHSearchBar Features

  • [set/get] cancelButtonTextAttributes

Search Bar height & remove separator

Hi Stefan,

thanks for your help and for developing and open sourcing this search bar!

I got the search bar working with a UITableView (even in swift 4.1) and it's great . I am trying to develop an airbnb style table view UI.

However, I am not able to do 2 things:

  1. Change the height of the Search Bar (to say 44)
  2. Remove the extra line below the Navigation Item Header (screenshot shared) so that it looks like the reference images attached

Airbnb Default View before Scrolling

default_searchbar_view

Airbnb View After Scrolling

after_scrolling

What I am able to accomplish

my_app

Pasting my code below which I incorporated from your examples.

Would be ammmmmmazing if I can make this happen!

class ContactListViewController: UITableViewController {
var searchBar: SHSearchBar!
  var viewConstraints: [NSLayoutConstraint]?
  var rasterSize: CGFloat = 11.0

  var contacts: Results<Contact>?
  
  override func viewDidLoad() {
    super.viewDidLoad()
    
    let searchGlassIconTemplate = UIImage(named: "icon-search")!.withRenderingMode(.alwaysTemplate)
    
    view.backgroundColor = UIColor.white
    
    // we need to set the title view to nil and get always the right frame
    navigationItem.titleView = nil
    
    // update properties of your custom title view
    searchBar = defaultSearchBar(withRasterSize: rasterSize,
                                           leftView: imageViewWithIcon(searchGlassIconTemplate, rasterSize: rasterSize),
                                           rightView: nil,
                                           delegate: self)
    
    let titleView = SearchbarTitleView(searchbar: searchBar)
    navigationItem.titleView = titleView
    
    let searchbarHeight: CGFloat = 44.0
    let constraints = [
      searchBar.heightAnchor.constraint(equalToConstant: searchbarHeight)
    ]
    NSLayoutConstraint.activate(constraints)
    
//    DispatchQueue.main.async {
//      self.fetchContacts()
//    }
    loadContacts()
  }
  
  func imageViewWithIcon(_ icon: UIImage, rasterSize: CGFloat) -> UIImageView {
    let imgView = UIImageView(image: icon)
    imgView.frame = CGRect(x: 0, y: 0, width: icon.size.width + rasterSize * 2.0, height: icon.size.height)
    imgView.contentMode = .center
    imgView.tintColor = UIColor(hexString: "#ce4e7f")
    return imgView
  }
  
  func defaultSearchBar(withRasterSize rasterSize: CGFloat, leftView: UIView?, rightView: UIView?, delegate: SHSearchBarDelegate, useCancelButton: Bool = true) -> SHSearchBar {
    var config = defaultSearchBarConfig(rasterSize)
    config.leftView = leftView
    config.rightView = rightView
    config.useCancelButton = useCancelButton
    
    if leftView != nil {
      config.leftViewMode = .always
    }
    
    if rightView != nil {
      config.rightViewMode = .unlessEditing
    }
    
    let bar = SHSearchBar(config: config)
    bar.delegate = delegate
    bar.placeholder = NSLocalizedString("Search by name or number", comment: "")
    bar.updateBackgroundImage(withRadius: 6, corners: [.allCorners], color: UIColor.white)
    bar.layer.shadowColor = UIColor.black.cgColor
    bar.layer.shadowOffset = CGSize(width: 0, height: 3)
    bar.layer.shadowRadius = 5
    bar.layer.shadowOpacity = 0.25
    return bar
  }
  
  func defaultSearchBarConfig(_ rasterSize: CGFloat) -> SHSearchBarConfig {
    var config: SHSearchBarConfig = SHSearchBarConfig()
    config.rasterSize = rasterSize
    config.cancelButtonTextAttributes = [.foregroundColor : UIColor.darkGray]
    config.textContentType = UITextContentType.fullStreetAddress.rawValue
    config.textAttributes = [.foregroundColor : UIColor.gray]
    return config
  }
}

๐Ÿšจ Fix Testing for SPM Packages

I cannot test atm:

module 'XCTest' was created for incompatible target x86_64-apple-macos10.15: /Applications/Xcode-GM.app/Contents/Developer/Platforms/MacOSX.platform/Developer/usr/lib/XCTest.swiftmodule/x86_64.swiftmodule
import XCTest

This should work
xcodebuild -scheme <scheme> test -sdk iphonesimulator -destination 'platform=iOS Simulator,name=iPhone 11'

Find your scheme name by executing:
xcodebuild -list

Compilation Issues: Key is not a member of NSAttributedString, etc

Stefan,

firstly kudos for building this Custom Search Bar! It's exactly what I was looking for and it's super slick, like in the Airbnb app. Also I saw that it can be used with the UITableView so thats perfect.

However, I am getting some issues in compiling when integrating with my project as well as compiling the sample app. Attaching a screenshot

My Xcode version is 9.4.1 and I checked that the Swift Version in the targets for the Pod was 4.1.
I cleared the app's derived data, then cleaned the code and rebuild but same issue.

What could I be missing? Really looking forward to using this pod.

build_errors_shsearchbar

Does not support storyboard

It could be an ultimate replace for UISearchBar, except for a very big minus. It seems not having a storyboard support, it crashes with "init(coder:) has not been implemented".

Fix config setting

Tried to fork your repo but github wouldn't let me :/

Right now you can't set the textContentType to nil on an existing searchbar. Fix suggestions:

Change

        if #available(iOS 10.0, *) {
            if let textContentType = config.textContentType {
                textField.textContentType = UITextContentType(rawValue: textContentType)
            }
        }

to

        if #available(iOS 10.0, *) {
            if let textContentType = config.textContentType {
                textField.textContentType = UITextContentType(rawValue: textContentType)
            } else {
                textField.textContentType = nil
            }
        }

pressedCancelButton resigns always without respecting the delegate

Current implementation:

func pressedCancelButton(_ sender: AnyObject) {
        textField.resignFirstResponder()
        _ = delegate?.searchBarShouldCancel?(self)
}

Better implementation:

func pressedCancelButton(_ sender: AnyObject) {
	if delegate?.searchBarShouldCancel?(self) ?? true {
		textField.resignFirstResponder()
	}
}

Can't Change Font

Whenever I set the font of the search bar, the font does change when the view initially loads. But, after a second the font resets. The placeholder text remains the custom font, but the font of the text typed goes back to default.

Add translations to all user-visible strings

Strings are currently not localised at all. To solve this issue you need to do the following steps:

  1. Create a Localizable.strings file and insert keys for all strings used in the project (there are only one or two).

  2. Add as much translations as you can.

Search bar set as title view in iOS 11

I'm setting the search bar as the title view of my navigation bar, however this doesn't seem to be working nicely. The text field isn't as large as the search bar, everything shrinks down. I also tried to subclass a UIView like this and add the search bar as a subview but things got a lot more weird. What can I do?

giphy

Project: Remove Config Object

The config object is user unfriendly. The SHSearchBar should own the properties.
This would even simplify the tests since now I tests are executed way too often and extremely redundant wich will bring performance issues in future.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.