Custom UISearchBar with UISearchController - ios

The documentation for UISearchController says that you can override - searchBar to provide a custom subclass of UISearchBar for the controller to use. The custom search bar does get used, and its own delegate methods are called correctly, but the UISearchResultsUpdating method no longer gets called when the search bar changes. Do I need to do a lot of wiring things up manually, or is there something I'm missing to get the controller to behave like it does with a natively supplied search bar?

Override the SearchBar getter in your custom UISearchController class, it have to return your custom SearchBar and it have to be already initialized, then you setup its properties only after the UISearchController init, this way all the UISearchController functionality are retained:
public class DSearchController: UISearchController {
private var customSearchBar = DSearchBar()
override public var searchBar: UISearchBar {
get {
return customSearchBar
}
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
public init(searchResultsController: UIViewController?,
searchResultsUpdater: UISearchResultsUpdating?,
delegate: UISearchControllerDelegate?,
dimsBackgroundDuringPresentation: Bool,
hidesNavigationBarDuringPresentation: Bool,
searchBarDelegate: UISearchBarDelegate?,
searchBarFrame: CGRect?,
searchBarStyle: UISearchBarStyle,
searchBarPlaceHolder: String,
searchBarFont: UIFont?,
searchBarTextColor: UIColor?,
searchBarBarTintColor: UIColor?, // Bar background
searchBarTintColor: UIColor) { // Cursor and bottom line
super.init(searchResultsController: searchResultsController)
self.searchResultsUpdater = searchResultsUpdater
self.delegate = delegate
self.dimsBackgroundDuringPresentation = dimsBackgroundDuringPresentation
self.hidesNavigationBarDuringPresentation = hidesNavigationBarDuringPresentation
customSearchBar.setUp(searchBarDelegate,
frame: searchBarFrame,
barStyle: searchBarStyle,
placeholder: searchBarPlaceHolder,
font: searchBarFont,
textColor: searchBarTextColor,
barTintColor: searchBarBarTintColor,
tintColor: searchBarTintColor)
}
}
And this is my custom searchBar:
public class DSearchBar: UISearchBar {
var preferredFont: UIFont?
var preferredTextColor: UIColor?
init(){
super.init(frame: CGRect.zero)
}
func setUp(delegate: UISearchBarDelegate?,
frame: CGRect?,
barStyle: UISearchBarStyle,
placeholder: String,
font: UIFont?,
textColor: UIColor?,
barTintColor: UIColor?,
tintColor: UIColor?) {
self.delegate = delegate
self.frame = frame ?? self.frame
self.searchBarStyle = searchBarStyle
self.placeholder = placeholder
self.preferredFont = font
self.preferredTextColor = textColor
self.barTintColor = barTintColor ?? self.barTintColor
self.tintColor = tintColor ?? self.tintColor
self.bottomLineColor = tintColor ?? UIColor.clearColor()
sizeToFit()
// translucent = false
// showsBookmarkButton = false
// showsCancelButton = true
// setShowsCancelButton(false, animated: false)
// customSearchBar.backgroundImage = UIImage()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
let bottomLine = CAShapeLayer()
var bottomLineColor = UIColor.clearColor()
override public func layoutSubviews() {
super.layoutSubviews()
for view in subviews {
if let searchField = view as? UITextField { setSearchFieldAppearance(searchField); break }
else {
for sView in view.subviews {
if let searchField = sView as? UITextField { setSearchFieldAppearance(searchField); break }
}
}
}
bottomLine.path = UIBezierPath(rect: CGRectMake(0.0, frame.size.height - 1, frame.size.width, 1.0)).CGPath
bottomLine.fillColor = bottomLineColor.CGColor
layer.addSublayer(bottomLine)
}
func setSearchFieldAppearance(searchField: UITextField) {
searchField.frame = CGRectMake(5.0, 5.0, frame.size.width - 10.0, frame.size.height - 10.0)
searchField.font = preferredFont ?? searchField.font
searchField.textColor = preferredTextColor ?? searchField.textColor
//searchField.backgroundColor = UIColor.clearColor()
//backgroundImage = UIImage()
}
}
Init example:
searchController = DSearchController(searchResultsController: ls,
searchResultsUpdater: self,
delegate: self,
dimsBackgroundDuringPresentation: true,
hidesNavigationBarDuringPresentation: true,
searchBarDelegate: ls,
searchBarFrame: CGRectMake(0.0, 0.0, SCREEN_WIDTH, 44.0),
searchBarStyle: .Minimal,
searchBarPlaceHolder: NSLocalizedString("Search a location...", comment: ""),
searchBarFont: nil,
searchBarTextColor: nil,
searchBarBarTintColor: UIColor.whiteColor(),
searchBarTintColor: iconsColor)
searchController.searchBar.keyboardAppearance = .Dark
definesPresentationContext = true
tableView.tableHeaderView = searchController.searchBar

This is a known bug. Unfortunately, there is no workaround that does not involve private API.

When you subclass UISearchController you can customise UISearchBar in getter (setter doesn't exist).
Example - in subclass implementation:
-(UISearchBar*)searchBar{
UISearchBar *baseSearchBar = [super searchBar];
if (baseSearchBar.showsScopeBar) {
baseSearchBar.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 88);
}else{
baseSearchBar.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 44);
}
return baseSearchBar;
}
Hope this helps someone.

I think it's supposed to behave like that.
This is from UISearchController.h
// You are free to become the search bar's delegate to monitor for text changes and button presses.
#property (nonatomic, retain, readonly) UISearchBar *searchBar;
All that delegate method (updateSearchResultsForSearchController:) does is return your search controller so you can access its search bar.
You can just do that through your custom search bar delegate methods.

Related

UISwitch ".onTintColor" and ".tintColor" not working [duplicate]

I've learned that we can change the UISwitch button appearance in its "on" state,
but is it also possible to change the color of the UISwitch in the "off" state?
My solution with #swift2:
let onColor = _your_on_state_color
let offColor = _your_off_state_color
let mSwitch = UISwitch(frame: CGRect.zero)
mSwitch.on = true
/*For on state*/
mSwitch.onTintColor = onColor
/*For off state*/
mSwitch.tintColor = offColor
mSwitch.layer.cornerRadius = mSwitch.frame.height / 2.0
mSwitch.backgroundColor = offColor
mSwitch.clipsToBounds = true
Result:
Try using this
yourSwitch.backgroundColor = [UIColor whiteColor];
youSwitch.layer.cornerRadius = 16.0;
All thanks to #Barry Wyckoff.
You can use the tintColor property on the switch.
switch.tintColor = [UIColor redColor]; // the "off" color
switch.onTintColor = [UIColor greenColor]; // the "on" color
Note this requires iOS 5+
Swift IBDesignable
import UIKit
#IBDesignable
class UISwitchCustom: UISwitch {
#IBInspectable var OffTint: UIColor? {
didSet {
self.tintColor = OffTint
self.layer.cornerRadius = 16
self.backgroundColor = OffTint
}
}
}
set class in Identity inspector
change color from Attributes inspector
Output
Here's a pretty good trick: you can just reach right into the UISwitch's subview that draws its "off" background, and change its background color. This works a lot better in iOS 13 than it does in iOS 12:
if #available(iOS 13.0, *) {
self.sw.subviews.first?.subviews.first?.backgroundColor = .green
} else if #available(iOS 12.0, *) {
self.sw.subviews.first?.subviews.first?.subviews.first?.backgroundColor = .green
}
Working 100% IOS 13.0 and Swift 5.0 switch both state color set same #ios13 #swift #swift5
#IBOutlet weak var switchProfile: UISwitch!{
didSet{
switchProfile.onTintColor = .red
switchProfile.tintColor = .red
switchProfile.subviews[0].subviews[0].backgroundColor = .red
}
}
The Best way to manage background color & size of UISwitch
For now it's Swift 2.3 code
import Foundation
import UIKit
#IBDesignable
class UICustomSwitch : UISwitch {
#IBInspectable var OnColor : UIColor! = UIColor.blueColor()
#IBInspectable var OffColor : UIColor! = UIColor.grayColor()
#IBInspectable var Scale : CGFloat! = 1.0
override init(frame: CGRect) {
super.init(frame: frame)
self.setUpCustomUserInterface()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.setUpCustomUserInterface()
}
func setUpCustomUserInterface() {
//clip the background color
self.layer.cornerRadius = 16
self.layer.masksToBounds = true
//Scale down to make it smaller in look
self.transform = CGAffineTransformMakeScale(self.Scale, self.Scale);
//add target to get user interation to update user-interface accordingly
self.addTarget(self, action: #selector(UICustomSwitch.updateUI), forControlEvents: UIControlEvents.ValueChanged)
//set onTintColor : is necessary to make it colored
self.onTintColor = self.OnColor
//setup to initial state
self.updateUI()
}
//to track programatic update
override func setOn(on: Bool, animated: Bool) {
super.setOn(on, animated: true)
updateUI()
}
//Update user-interface according to on/off state
func updateUI() {
if self.on == true {
self.backgroundColor = self.OnColor
}
else {
self.backgroundColor = self.OffColor
}
}
}
Swift 5:
import UIKit
extension UISwitch {
func set(offTint color: UIColor ) {
let minSide = min(bounds.size.height, bounds.size.width)
layer.cornerRadius = minSide / 2
backgroundColor = color
tintColor = color
}
}
Should you need other switches around your app, it might be also a good idea implementing #LongPham's code inside a custom class.
As others have pointed out, for the "off" state you'll need to change the background colour as well, since the default is transparent.
class MySwitch: UISwitch {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
// Setting "on" state colour
self.onTintColor = UIColor.green
// Setting "off" state colour
self.tintColor = UIColor.red
self.layer.cornerRadius = self.frame.height / 2
self.backgroundColor = UIColor.red
}
}
Swift 4 easiest and fastest way to get it in 3 steps:
// background color is the color of the background of the switch
switchControl.backgroundColor = UIColor.white.withAlphaComponent(0.9)
// tint color is the color of the border when the switch is off, use
// clear if you want it the same as the background, or different otherwise
switchControl.tintColor = UIColor.clear
// and make sure that the background color will stay in border of the switch
switchControl.layer.cornerRadius = switchControl.bounds.height / 2
If you manually change the size of the switch (e.g., by using autolayout), you will have to update the switch.layer.cornerRadius too, e.g., by overriding layoutSubviews and after calling super updating the corner radius:
override func layoutSubviews() {
super.layoutSubviews()
switchControl.layer.cornerRadius = switchControl.bounds.height / 2
}
In Swift 4+:
off state:
switch.tintColor = UIColor.blue
on state:
switch.onTintColor = UIColor.red
The UISwitch offTintColor is transparent, so whatever is behind the switch shows through. Therefore, instead of masking the background color, it suffices to draw a switch-shaped image behind the switch (this implementation assumes that the switch is positioned by autolayout):
func putColor(_ color: UIColor, behindSwitch sw: UISwitch) {
guard sw.superview != nil else {return}
let onswitch = UISwitch()
onswitch.isOn = true
let r = UIGraphicsImageRenderer(bounds:sw.bounds)
let im = r.image { ctx in
onswitch.layer.render(in: ctx.cgContext)
}.withRenderingMode(.alwaysTemplate)
let iv = UIImageView(image:im)
iv.tintColor = color
sw.superview!.insertSubview(iv, belowSubview: sw)
iv.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
iv.topAnchor.constraint(equalTo: sw.topAnchor),
iv.bottomAnchor.constraint(equalTo: sw.bottomAnchor),
iv.leadingAnchor.constraint(equalTo: sw.leadingAnchor),
iv.trailingAnchor.constraint(equalTo: sw.trailingAnchor),
])
}
[But see now my other answer.]
2020 As of Xcode 11.3.1 & Swift 5
Here's the simplest way I've found of doing setting the UISwitch off-state colour with one line of code. Writing this here since this page is what came up first when I was looking and the other answers didn't help.
This is if I wanted to set the off state to be red, and can be added to the viewDidLoad() function:
yourSwitchName.subviews[0].subviews[0].backgroundColor = UIColor.red
Note - what this is actually doing is setting the background colour of the switch. This may influence the colour of the switch in the on-state too (though for me this wasn't a problem since I wanted the on and off state to be the same colour).
A solution for this:
Simply tie in the colours with an 'if else' statement inside your IBAction. If the switch is off, colour the background red. If the switch is on, leave the background clear so your chosen 'on' colour will display properly.
This goes inside the switch IBAction.
if yourSwitch.isOn == false {
yourSwitch.subviews[0].subviews[0].backgroundColor = UIColor.red
} else {
yourSwitch.subviews[0].subviews[0].backgroundColor = UIColor.clear
}
I found some behaviour where, upon the app resuming from background, the switch background would return to clear. To remedy this problem I simply added in the following code to set the colour every time the app comes to the foreground:
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
NotificationCenter.default.addObserver(
self,
selector: #selector(applicationWillEnterForeground(_:)),
name: UIApplication.willEnterForegroundNotification,
object: nil)
}
#objc func applicationWillEnterForeground(_ notification: NSNotification) {
yourSwitch.subviews[0].subviews[0].backgroundColor = UIColor.red
yourSwitch.subviews[0].subviews[0].backgroundColor = UIColor.red
}
Seems simpler than the other answers. Hope that helps!
More safe way in Swift 3 without magical 16pt values:
class ColoredBackgroundSwitch: UISwitch {
var offTintColor: UIColor {
get {
return backgroundColor ?? UIColor.clear
}
set {
backgroundColor = newValue
}
}
override func layoutSubviews() {
super.layoutSubviews()
let minSide = min(frame.size.height, frame.size.width)
layer.cornerRadius = ceil(minSide / 2)
}
}
objective c category to use on any UISwitch in project using code or storyboard:
#import <UIKit/UIKit.h>
#interface UISwitch (SAHelper)
#property (nonatomic) IBInspectable UIColor *offTint;
#end
implementation
#import "UISwitch+SAHelper.h"
#implementation UISwitch (SAHelper)
#dynamic offTint;
- (void)setOffTint:(UIColor *)offTint {
self.tintColor = offTint; //comment this line to hide border in off state
self.layer.cornerRadius = 16;
self.backgroundColor = offTint;
}
#end
XCode 11, Swift 5
I don't prefer using subViews, cause you never know when apple gonna change the hierarchy.
so I use mask view instead.
it works with iOS 12, iOS 13
private lazy var settingSwitch: UISwitch = {
let swt: UISwitch = UISwitch()
// set border color when isOn is false
swt.tintColor = .cloudyBlueTwo
// set border color when isOn is true
swt.onTintColor = .greenishTeal
// set background color when isOn is false
swt.backgroundColor = .cloudyBlueTwo
// create a mask view to clip background over the size you expected.
let maskView = UIView(frame: swt.frame)
maskView.backgroundColor = .red
maskView.layer.cornerRadius = swt.frame.height / 2
maskView.clipsToBounds = true
swt.mask = maskView
// set the scale to your expectation, here is around height: 34, width: 21.
let scale: CGFloat = 2 / 3
swt.transform = CGAffineTransform(scaleX: scale, y: scale)
swt.addTarget(self, action: #selector(switchOnChange(_:)), for: .valueChanged)
return swt
}()
#objc
func switchOnChange(_ sender: UISwitch) {
if sender.isOn {
// set background color when isOn is true
sender.backgroundColor = .greenishTeal
} else {
// set background color when isOn is false
sender.backgroundColor = .cloudyBlueTwo
}
}
I tested on IOS 14, set background as off color and onTintColor as On and works:
uiSwitch.onTintColor = UIColor.blue
uiSwitch.backgroundColor = UIColor.red
XCode 11, Swift 4.2
Starting with Matt's solution I added it to a custom, IBDesignable control. There is a timing issue in that didMoveToSuperview() is called before the offTintColor is set that needed to be handled.
#IBDesignable public class UISwitchCustom: UISwitch {
var switchMask: UIImageView?
private var observers = [NSKeyValueObservation]()
#IBInspectable dynamic var offTintColor : UIColor! = UIColor.gray {
didSet {
switchMask?.tintColor = offTintColor
}
}
override init(frame: CGRect) {
super.init(frame: frame)
initializeObservers()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initializeObservers()
}
private func initializeObservers() {
observers.append(observe(\.isHidden, options: [.initial]) {(model, change) in
self.switchMask?.isHidden = self.isHidden
})
}
override public func didMoveToSuperview() {
addOffColorMask(offTintColor)
super.didMoveToSuperview()
}
private func addOffColorMask(_ color: UIColor) {
guard self.superview != nil else {return}
let onswitch = UISwitch()
onswitch.isOn = true
let r = UIGraphicsImageRenderer(bounds:self.bounds)
let im = r.image { ctx in
onswitch.layer.render(in: ctx.cgContext)
}.withRenderingMode(.alwaysTemplate)
let iv = UIImageView(image:im)
iv.tintColor = color
self.superview!.insertSubview(iv, belowSubview: self)
iv.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
iv.topAnchor.constraint(equalTo: self.topAnchor),
iv.bottomAnchor.constraint(equalTo: self.bottomAnchor),
iv.leadingAnchor.constraint(equalTo: self.leadingAnchor),
iv.trailingAnchor.constraint(equalTo: self.trailingAnchor),
])
switchMask = iv
switchMask?.isHidden = self.isHidden
}
}
all I finally used transform and layer.cornerRadius too.
But I have added translation to it to be center.
private func setSwitchSize() {
let iosSwitchSize = switchBlockAction.bounds.size
let requiredSwitchSize = ...
let transform = CGAffineTransform(a: requiredSwitchSize.width / iosSwitchSize.width, b: 0,
c: 0, d: requiredSwitchSize.height / iosSwitchSize.height,
tx: (requiredSwitchSize.width - iosSwitchSize.width) / 2.0,
ty: (requiredSwitchSize.height - iosSwitchSize.height) / 2.0)
switchBlockAction.layer.cornerRadius = iosSwitchSize.height / 2.0
switchBlockAction.transform = transform
}
And I did use backgroundColor and tintColor in designer.
Hope it helps.

Changing Search Bar placeholder text colour in iOS 13

I'm trying to set colour for placeholder text inside UISearchbar. Right now I've following code. It doesn't set white colour to placeholder text on iOS 13. It works on iOS 12. It seems something is either broken or support has been removed in iOS 13?
I've searched a lot and tried few workarounds but doesn't work. I've also tried to set attributed text colour for textfield but that also doesn't change colour.
Is there a working solution for this?
class CustomSearchBar: UISearchBar {
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func awakeFromNib() {
super.awakeFromNib()
self.sizeToFit()
// Search text colour change
let textFieldInsideSearchBar = self.value(forKey: "searchField") as? UITextField
textFieldInsideSearchBar?.textColor = UIColor.white
// Search Placeholder text colour change
let placeHolderText = textFieldInsideSearchBar!.value(forKey: "placeholderLabel") as? UILabel
placeHolderText?.textColor = UIColor.white // doesn't work
}
}
viewDidLoad is too early
Put the code in viewDidAppear, viewDidLoad is too early. Then your placeholder should change to white
searchController.searchBar.searchTextField.attributedPlaceholder = NSAttributedString(string: "Enter Search Here", attributes: [NSAttributedString.Key.foregroundColor : UIColor.white])
In viewDidAppear
if iOS is higher than 13.0, use searchBar.searchTextField.attributedPlaceholder.
if iOS is lower than 13.0, use searchBar.value(forKey: "searchField") to access searchTextField
var searchBar = UISearchBar()
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if #available(iOS 13.0, *) {
searchBar.searchTextField.attributedPlaceholder = NSAttributedString(string: "Enter Search Here", attributes: [NSAttributedString.Key.foregroundColor : UIColor.white])
} else {
if let searchField = searchBar.value(forKey: "searchField") as? UITextField {
searchField.attributedPlaceholder = NSAttributedString(string: "Enter Search Here", attributes: [NSAttributedString.Key.foregroundColor: UIColor.white2])
}
}
}
Try this:
var searchBar: UISearchBar!
if let textfield = searchBar.value(forKey: "searchField") as? UITextField {
textfield.attributedPlaceholder = NSAttributedString(string: textfield.placeholder ?? "", attributes: [NSAttributedString.Key.foregroundColor : UIColor.white])
}
Please add this extension and try this !
extension UISearchBar{
var placeholderLabel: UILabel? { return value(forKey: "placeholderLabel") as? UILabel }
func setPlaceholder(textColor: UIColor) {
guard let placeholderLabel = placeholderLabel else { return }
let label = Label(label: placeholderLabel, textColor: textColor)
placeholderLabel.removeFromSuperview() // To remove existing label. Otherwise it will overwrite it if called multiple times.
setValue(label, forKey: "placeholderLabel")
}
}
private extension UITextField {
private class Label: UILabel {
private var _textColor = UIColor.lightGray
override var textColor: UIColor! {
set { super.textColor = _textColor }
get { return _textColor }
}
init(label: UILabel, textColor: UIColor = .lightGray) {
_textColor = textColor
super.init(frame: label.frame)
self.text = label.text
self.font = label.font
}
required init?(coder: NSCoder) { super.init(coder: coder) }
}
Usage
yourSearchBarObject.setPlaceholder(textColor: .red)
You need to style everything in viewDidAppear

UISearchBar jumping out of position once tapped

I am trying to display a MySearchBar (UISearchBar with added UILabel to display the title) as the navigationItem's view:
// Make search bar autoresize and occupy maximum width
self.navigationItem.titleView = [[UIView alloc] initWithFrame:self.navigationController.navigationBar.bounds];
self.navigationItem.titleView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
[self.navigationItem.titleView addSubview:self.mySearchBar.view];
self.mySearchBar.view.frame = self.navigationItem.titleView.frame;
The search bar sits in place until it is tapped. After tapping, it moves down and it no longer occupies full width (around 16px are missing).
Before editing (how it should look):
Editing began (BUG - after tapping the search bar grows in height to the default 56px and loses width):
Editing ended (remains misplaced)
Here is the initialization code of MySearchBar. It consists of two main views, titleView wraps the UILabel with title and searchBarWrapperView wraps the UISearchBar:
-(id) init {
// Initialize the two wrapping views
UIView *titleView = [UIView new];
self.searchBarWrapperView = [UIView new];
// Resize UILabel to fit its content
self.titleLabel = [UILabel new];
self.titleLabel.numberOfLines = 0;
[self.titleLabel sizeToFit];
self.searchBar = self.searchController.searchBar;
self.searchBarTextField = [self.searchBar valueForKey:#"searchField"];// This could be the text field that gets displaced???
// Add two main subviews (wrappers)
[self.view addSubview:titleView];
[self.view addSubview:self.searchBarWrapperView];
// Add title label and search bar to the subviews
[titleView addSubview:self.titleLabel];
[self.searchBarWrapperView addSubview:self.searchBar];
// Disable auto constraints
[titleView setTranslatesAutoresizingMaskIntoConstraints:NO];
[self.searchBarWrapperView setTranslatesAutoresizingMaskIntoConstraints:NO];
[self.titleLabel setTranslatesAutoresizingMaskIntoConstraints:NO];
// Set constraints for title view
[titleView.topAnchor constraintEqualToAnchor:self.view.topAnchor].active = YES;
[titleView.leftAnchor constraintEqualToAnchor:self.view.leftAnchor].active = YES;
[titleView.rightAnchor constraintEqualToAnchor:self.view.rightAnchor].active = YES;
[titleView.bottomAnchor constraintEqualToAnchor:self.titleLabel.bottomAnchor].active = YES;
// Set constraints for title label
[self.titleLabel.topAnchor constraintEqualToAnchor:titleView.topAnchor].active = YES;
[self.titleLabel.leftAnchor constraintEqualToAnchor:titleView.leftAnchor].active = YES;
[self.titleLabel.rightAnchor constraintEqualToAnchor:titleView.rightAnchor].active = YES;
// Set constraints for search bar wrapper
[self.searchBarWrapperView.heightAnchor constraintGreaterThanOrEqualToConstant:30].active = YES;// The search bar together with the title label should occupy the whole 44px height of the navigation bar
[self.searchBarWrapperView.topAnchor constraintEqualToAnchor:titleView.bottomAnchor].active = YES;
[self.searchBarWrapperView.bottomAnchor constraintEqualToAnchor:self.view.bottomAnchor].active = YES;
[self.searchBarWrapperView.leftAnchor constraintEqualToAnchor:self.view.leftAnchor].active = YES;
[self.searchBarWrapperView.rightAnchor constraintEqualToAnchor:self.view.rightAnchor constant:16].active = YES;// Add space that is lost by setSearchFieldBackgroundPositionAdjustment
// Configure autoresizing mask for UISearchBar
[self.searchBar setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight];
[self.searchBar setFrame:self.searchBarWrapperView.frame];
//Remove left and right blank spaces around UISearchBar
[self.searchBar setSearchFieldBackgroundPositionAdjustment:UIOffsetMake(-8,0)];
// Colors for debugging
self.view.backgroundColor = [UIColor blueColor];
titleView.backgroundColor = [UIColor redColor];
searchBarWrapperView.backgroundColor = [UIColor greenColor];
self.searchBar.backgroundColor = [UIColor yellowColor];
self.searchBarTextField.backgroundColor = [UIColor brownColor];
return self;
}
The solution I used was to subclass the UISearchBar and the UISearchController. That way I can set the frame and control the search bar events.
SearchBar.swift:
import Foundation
class SearchBar : UISearchBar {
var preferredFont:UIFont?
var preferredTextColor:UIColor?
init(frame: CGRect, font: UIFont, textColor: UIColor) {
super.init(frame: frame)
self.frame = frame
self.preferredFont = font
self.preferredTextColor = textColor
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
}
}
SearchController.swift:
import Foundation
protocol SearchControllerDelegate {
func didStartSearching()
func didTapOnSearchButton()
func didTapOnCancelButton()
func didChangeSearchText(searchText: String)
}
class SearchController : UISearchController, UISearchBarDelegate, SearchControllerDelegate {
var customSearchBar: SearchBar!
var customDelegate: SearchControllerDelegate!
init(searchResultsController: UIViewController!, searchBarFrame: CGRect, searchBarFont: UIFont, searchBarTextColor: UIColor, searchBarTintColor: UIColor) {
super.init(searchResultsController: searchResultsController)
configureSearchBar(frame: searchBarFrame, font: searchBarFont, textColor: searchBarTextColor, bgColor: searchBarTintColor)
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
}
func configureSearchBar(frame: CGRect, font: UIFont, textColor: UIColor, bgColor: UIColor) {
self.customSearchBar = SearchBar(frame: frame, font: font , textColor: textColor)
self.customSearchBar.placeholder = "Search"
self.customSearchBar.barTintColor = bgColor
self.customSearchBar.tintColor = textColor
self.customSearchBar.showsBookmarkButton = false
self.customSearchBar.showsCancelButton = false
self.customSearchBar.delegate = self
self.customDelegate = self;
let searchBarTextField:UITextField = self.customSearchBar.value(forKey: "searchField") as! UITextField
searchBarTextField.font = font
searchBarTextField.layer.borderWidth = 1
searchBarTextField.layer.cornerRadius = 3
searchBarTextField.layer.borderColor = UIColor.lightGray.cgColor
}
// UISearchBarDelegate
func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
customDelegate.didStartSearching()
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
customSearchBar.resignFirstResponder()
customDelegate.didTapOnSearchButton()
}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
customSearchBar.resignFirstResponder()
customDelegate.didTapOnCancelButton()
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
customDelegate.didChangeSearchText(searchText: searchText)
}
// SearchControllerDelegate
func didStartSearching() {
}
func didTapOnSearchButton() {
var searchText:String = ""
if (self.customSearchBar.text != nil) {
searchText = self.customSearchBar.text!
}
self.search(searchQuery: searchText)
}
func didTapOnCancelButton() {
}
func didChangeSearchText(searchText: String) {
self.search(searchQuery: searchText)
}
// Search
func search(searchQuery: String) {
// Start searching
}
}

Best way to position UIToolbar programmatically (with or without UIToolbarDelegate)?

I'm implementing in Playgound a segmented control underneath the navigation bar.
This seems to be a classic problem, which has been asked:
UISegmentedControl below UINavigationbar in iOS 7
Add segmented control to navigation bar and keep title with buttons
In the doc of UIBarPositioningDelegate, it says,
The UINavigationBarDelegate, UISearchBarDelegate, and
UIToolbarDelegate protocols extend this protocol to allow for the
positioning of those bars on the screen.
And In the doc of UIBarPosition:
case top
Specifies that the bar is at the top of its containing view.
In the doc of UIToolbar.delegate:
You may not set the delegate when the toolbar is managed by a
navigation controller. The default value is nil.
My current solution is as below (the commented-out code are kept for reference and convenience):
import UIKit
import PlaygroundSupport
class ViewController : UIViewController, UIToolbarDelegate
{
let toolbar : UIToolbar = {
let ret = UIToolbar()
let segmented = UISegmentedControl(items: ["Good", "Bad"])
let barItem = UIBarButtonItem(customView: segmented)
ret.setItems([barItem], animated: false)
return ret
}()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(toolbar)
// toolbar.delegate = self
}
override func viewDidLayoutSubviews() {
toolbar.frame = CGRect(
x: 0,
y: navigationController?.navigationBar.frame.height ?? 0,
width: navigationController?.navigationBar.frame.width ?? 0,
height: 44
)
}
func position(for bar: UIBarPositioning) -> UIBarPosition {
return .topAttached
}
}
//class Toolbar : UIToolbar {
// override var barPosition: UIBarPosition {
// return .topAttached
// }
//}
let vc = ViewController()
vc.title = "Try"
vc.view.backgroundColor = .red
// Another way to add toolbar...
// let segmented = UISegmentedControl(items: ["Good", "Bad"])
// let barItem = UIBarButtonItem(customView: segmented)
// vc.toolbarItems = [barItem]
// Navigation Controller
let navVC = UINavigationController(navigationBarClass: UINavigationBar.self, toolbarClass: UIToolbar.self)
navVC.pushViewController(vc, animated: true)
navVC.preferredContentSize = CGSize(width: 375, height: 640)
// navVC.isToolbarHidden = false
// Page setup
PlaygroundPage.current.liveView = navVC
PlaygroundPage.current.needsIndefiniteExecution = true
As you can see, this doesn't use a UIToolbarDelegate.
How does a UIToolbarDelegate (providing the position(for:)) come into play in this situation? Since we can always position ourselves (either manually or using Auto Layout), what's the use case of a UIToolbarDelegate?
#Leo Natan's answer in the first question link above mentioned the UIToolbarDelegate, but it seems the toolbar is placed in Interface Builder.
Moreover, if we don't use UIToolbarDelegate here, why don't we just use a plain UIView instead of a UIToolbar?
Try this
UIView *containerVw = [[UIView alloc] initWithFrame:CGRectMake(0, 64, 320, 60)];
containerVw.backgroundColor = UIColorFromRGB(0xffffff);
[self.view addSubview:containerVw];
UIView *bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, 124, 320, 1)];
bottomView.backgroundColor = [UIColor grayColor];
[self.view addSubview:bottomView];
UISegmentedControl *sg = [[UISegmentedControl alloc] initWithItems:#[#"Good", #"Bad"]];
sg.frame = CGRectMake(10, 10, 300, 40);
[view addSubview:sg];
for (UIView *view in self.navigationController.navigationBar.subviews) {
for (UIView *subView in view.subviews) {
[subView isKindOfClass:[UIImageView class]];
subView.hidden = YES;
}
}
By setting the toolbar's delegate and by having the delegate method return .top, you get the normal shadow at the bottom of the toolbar. If you also adjust the toolbars frame one point higher, it will cover the navbar's shadow and the final result will be what appears to be a taller navbar with a segmented control added.
class ViewController : UIViewController, UIToolbarDelegate
{
lazy var toolbar: UIToolbar = {
let ret = UIToolbar()
ret.delegate = self
let segmented = UISegmentedControl(items: ["Good", "Bad"])
let barItem = UIBarButtonItem(customView: segmented)
ret.setItems([barItem], animated: false)
return ret
}()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(toolbar)
toolbar.delegate = self
}
override func viewDidLayoutSubviews() {
toolbar.frame = CGRect(
x: 0,
y: navigationController?.navigationBar.frame.height - 1 ?? 0,
width: navigationController?.navigationBar.frame.width ?? 0,
height: toolbar.frame.height
)
}
func position(for bar: UIBarPositioning) -> UIBarPosition {
return .top
}
}
How does a UIToolbarDelegate (providing the position(for:)) come into play in this situation? Since we can always position ourselves (either manually or using Auto Layout), what's the use case of a UIToolbarDelegate?
I sincerely do not know how the UIToolbarDelegate comes into play, if you change the UINavigationController.toolbar it will crashes with "You cannot set UIToolbar delegate managed by the UINavigationController manually", moreover the same will happen if you try to change the toolbar's constraint or its translatesAutoresizingMaskIntoConstraints property.
Moreover, if we don't use UIToolbarDelegate here, why don't we just use a plain UIView instead of a UIToolbar?
It seems to be a reasonable question. I guess the answer for this is that you have a UIView subclass which already has the behaviour of UIToolbar, so why would we create another class-like UIToolbar, unless you just want some view below the navigation bar.
There are 2 options that I'm aware of.
1) Related to Move UINavigationController's toolbar to the top to lie underneath navigation bar
The first approach might help when you have to show the toolbar in other ViewControllers that are managed by your NavigationController.
You can subclass UINavigationController and change the Y-axis position of the toolbar when the value is set.
import UIKit
private var context = 0
class NavigationController: UINavigationController {
private var inToolbarFrameChange = false
var observerBag: [NSKeyValueObservation] = []
override func awakeFromNib() {
super.awakeFromNib()
self.inToolbarFrameChange = false
}
override func viewDidLoad() {
super.viewDidLoad()
observerBag.append(
toolbar.observe(\.center, options: .new) { toolbar, _ in
if !self.inToolbarFrameChange {
self.inToolbarFrameChange = true
toolbar.frame = CGRect(
x: 0,
y: self.navigationBar.frame.height + UIApplication.shared.statusBarFrame.height,
width: toolbar.frame.width,
height: toolbar.frame.height
)
self.inToolbarFrameChange = false
}
}
)
}
override func setToolbarHidden(_ hidden: Bool, animated: Bool) {
super.setToolbarHidden(hidden, animated: false)
var rectTB = self.toolbar.frame
rectTB = .zero
}
}
2) You can create your own UIToolbar and add it to view of the UIViewController. Then, you add the constraints to the leading, trailing and the top of the safe area.
import UIKit
final class ViewController: UIViewController {
private let toolbar = UIToolbar()
private let segmentedControl: UISegmentedControl = {
let control = UISegmentedControl(items: ["Op 1", "Op 2"])
control.isEnabled = false
return control
}()
override func loadView() {
super.loadView()
setupToolbar()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.navigationBar.hideBorderLine()
}
private func setupToolbar() {
let barItem = UIBarButtonItem(customView: segmentedControl)
toolbar.setItems([barItem], animated: false)
toolbar.isTranslucent = false
toolbar.isOpaque = false
view.addSubview(toolbar)
toolbar.translatesAutoresizingMaskIntoConstraints = false
toolbar.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
toolbar.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
toolbar.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true
}
}
private extension UINavigationBar {
func showBorderLine() {
findBorderLine().isHidden = false
}
func hideBorderLine() {
findBorderLine().isHidden = true
}
private func findBorderLine() -> UIImageView! {
return self.subviews
.flatMap { $0.subviews }
.compactMap { $0 as? UIImageView }
.filter { $0.bounds.size.width == self.bounds.size.width }
.filter { $0.bounds.size.height <= 2 }
.first
}
}

Admob Native Advanced Not Clickable

I have created a custom View Class that inherits from GADNativeContentAdView Class. When I receive an advertisement and the delegate is called, I fill my custom view with the data as shown below.
Everything looks fine but the problem is that it is not clickable at all. I tried to set the actionbutton userinteraction to false, but still won't work.
I also tried to register using following:
-(void)registerAdView:(UIView *)adView
clickableAssetViews:(NSDictionary *)clickableAssetViews
nonclickableAssetViews:
(NSDictionary *)nonclickableAssetViews;
Any idea how to get it to work?
- (void)setNativeContent:(GADNativeContentAd *)nativeContent
{
self.nativeContentAd = nativeContent;
headlineLabel.text = nativeContent.headline;
bodyLabel.text = nativeContent.body;
advertiserImage.image = ((GADNativeAdImage *)nativeContent.images.firstObject).image;
[actionButton setTitle:nativeContent.callToAction forState:UIControlStateNormal];
if (nativeContent.logo && nativeContent.logo.image)
{
advertiserLogo.image = nativeContent.logo.image;
}
else
{
advertiserLogo.image = advertiserImage.image;
}
NSDictionary *clickableArea = #{GADNativeContentHeadlineAsset:headlineLabel, GADNativeContentImageAsset:advertiserImage, GADNativeContentCallToActionAsset:actionButton};
NSDictionary *nonClickableArea = #{GADNativeContentBodyAsset:bodyLabel};
[nativeContent registerAdView:self clickableAssetViews:clickableArea nonclickableAssetViews:nonClickableArea];
}
I finally figured out a way to make the entire native ad clickable without using a .xib. I subclassed GADNativeContentAdView and created a tappableOverlay view that I assigned to an unused asset view in its superclass. In this case, it was the callToActionView. Then I used the not-so-documented GADNativeContentAd.registerAdView() method:
- (void)registerAdView:(UIView *)adView
clickableAssetViews:(NSDictionary<GADNativeContentAdAssetID, UIView *> *)clickableAssetViews
nonclickableAssetViews: (NSDictionary<GADNativeContentAdAssetID, UIView *> *)nonclickableAssetViews;
Here's a Swift 4 example:
class NativeContentAdView: GADNativeContentAdView {
var nativeAdAssets: NativeAdAssets?
private let myImageView: UIImageView = {
let myImageView = UIImageView()
myImageView.translatesAutoresizingMaskIntoConstraints = false
myImageView.contentMode = .scaleAspectFill
myImageView.clipsToBounds = true
return myImageView
}()
private let myHeadlineView: UILabel = {
let myHeadlineView = UILabel()
myHeadlineView.translatesAutoresizingMaskIntoConstraints = false
myHeadlineView.numberOfLines = 0
myHeadlineView.textColor = .black
return myHeadlineView
}()
private let tappableOverlay: UIView = {
let tappableOverlay = UIView()
tappableOverlay.translatesAutoresizingMaskIntoConstraints = false
tappableOverlay.isUserInteractionEnabled = true
return tappableOverlay
}()
private let adAttribution: UILabel = {
let adAttribution = UILabel()
adAttribution.translatesAutoresizingMaskIntoConstraints = false
adAttribution.text = "Ad"
adAttribution.textColor = .white
adAttribution.textAlignment = .center
adAttribution.backgroundColor = UIColor(red: 1, green: 0.8, blue: 0.4, alpha: 1)
adAttribution.font = UIFont.systemFont(ofSize: 11, weight: UIFont.Weight.semibold)
return adAttribution
}()
override var nativeContentAd: GADNativeContentAd? {
didSet {
if let nativeContentAd = nativeContentAd, let callToActionView = callToActionView {
nativeContentAd.register(self,
clickableAssetViews: [GADNativeContentAdAssetID.callToActionAsset: callToActionView],
nonclickableAssetViews: [:])
}
}
}
init() {
super.init(frame: CGRect.zero)
translatesAutoresizingMaskIntoConstraints = false
backgroundColor = .white
isUserInteractionEnabled = true
callToActionView = tappableOverlay
headlineView = myHeadlineView
imageView = myImageView
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func didMoveToSuperview() {
super.didMoveToSuperview()
addSubview(myHeadlineView)
addSubview(myImageView)
addSubview(adAttribution)
addSubview(tappableOverlay)
}
// override func updateConstraints() {
// ....
// }
}
Just be sure to pin the tappableOverlay to its superview edges so that they're the same size...in updateConstraints().
Inside the method simply you can create and place Ad in view hierarchy.
GADNativeContentAdView *contentAdView = [[NSBundle mainBundle] loadNibNamed:#"NativeAdView" owner:nil options:nil].firstObject;
After assigning the properties, associate the content Ad view with the content ad object. This is required to make the ad clickable.
contentAdView.nativeContentAd = nativeContentAd;
Only AdMob whitelisted publishers can use the registerAdView API :)
All publishers can use xib to create an ad view.
Don't forget to link custom GADUnifiedNativeAdView outlets to your UILabels, UIButtons and ImageViews, so GADUnifiedNativeAdView will know what to interact with
In my case it was cause I created my views without xib.
In this case just set mediaView property to your GADNativeAdView
here the minimum working code
final class EndBannerController: UIViewController {
private let adId: String
private let adView = GADNativeAdView()
private let mediaView = GADMediaView()
private var adLoader: GADAdLoader?
init(adId: String) {
self.adId = adId
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) { return nil }
override func viewDidLoad() {
super.viewDidLoad()
adView.frame = view.bounds
view.addSubview(adView)
mediaView.frame = view.bounds
adView.mediaView = mediaView
adView.addSubview(mediaView)
let loader = GADAdLoader(
adUnitID: adId,
rootViewController: self,
adTypes: [.native],
options: nil
)
loader.delegate = self
self.adLoader = loader
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.loadBannerAd()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
adView.frame = view.bounds
mediaView.frame = view.bounds
}
private func loadBannerAd() {
let request = GADRequest()
request.scene = view.window?.windowScene
self.adLoader?.load(request)
}
}

Resources