#StackBounty: #ios #swift #uisearchbar #uisearchcontroller #uisearchresultscontroller UISearchBar's height is incorrect when presen…

Bounty: 50

I have a search bar in tableView’s header view, and I don’t change the height of it(default is 56pt). When search bar is active and its position goes top of the screen, it’s height becomes 50pt. It will both happen on iPhone or simulator, version iOS 11.

First appear:

<UISearchBar: 0x7f94b6646900; frame = (0 0; 375 56); text = ''; gestureRecognizers = <NSArray: 0x60400025fc20>; layer = <CALayer: 0x604000225fe0>>


<UISearchBar: 0x7f94b6646900; frame = (0 14; 375 50); text = ''; autoresize = W+TM; gestureRecognizers = <NSArray: 0x60400025fc20>; layer = <CALayer: 0x604000225fe0>>

It results in a weird gap between the search bar and result controller’s view.

Thanks for any ideas.

Here’s my code:

fileprivate func configSearchBar() -> Void {
    let bar = self.searchBar
    var size = bar.frame.size

    let statusBarHeight = UIApplication.shared.statusBarFrame.size.height
    bar.setBackgroundImage(UIImage.imageWith(color: .white, size: size),
                           for: .any,
                           barMetrics: .default)
    let colorWhenEditing = UIColor.colorFromHexString("#FAFAFA")
    if UIDevice.isIPHONEX() {
        bar.barTintColor = colorWhenEditing
    } else {
        bar.setBackgroundImage(UIImage.imageWith(color: colorWhenEditing, size: CGSize(width: size.width, height: size.height + statusBarHeight)),
                               for: .topAttached,
                               barMetrics: .default)
    size = CGSize(width: bar.frame.size.width - 30, height: 30)
    let image = UIImage.imageWith(color: UIColor(hexString: "#F0F0F0"), size: size)?.zoom(toSize: size, cornerRadius: 4)
    bar.setSearchFieldBackgroundImage(image, for: .normal)

    bar.searchTextPositionAdjustment = UIOffset(horizontal: 5, vertical: 0)

self.tableView.tableHeaderView = self.searchBar

Edit2: – Search controller and search bar initialization:

// Main view controller
lazy var searchResultController: UISearchController = {
    let vc = MailSearchResultViewController(nibName: nil, bundle: nil)
    let sc = UISearchController(searchResultsController: vc)
    sc.searchResultsUpdater = self
    sc.modalPresentationCapturesStatusBarAppearance = true
    sc.delegate = self
    return sc
var searchBar: UISearchBar {
    return searchResultController.searchBar
// MailSearchResultViewController - viewDidLoad:
self.edgesForExtendedLayout = []
self.automaticallyAdjustsScrollViewInsets = false

Get this bounty!!!

#StackBounty: #swift #uinavigationbar #uisplitviewcontroller UISplitView's MasterViewController and Navigation Issue

Bounty: 50

I am updating my existing app to include a SplitView for iPads.

I have it working with a UITabBar, but am having an issue with my masterViewController as it is generating a “duplicate” navigation bar that is covering my existing navigation items on all masterViewControllers (tabs), including searchBar on the search tab.

The code I have is:


class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate {

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool

    let splitViewController = self.window!.rootViewController as! UISplitViewController
    splitViewController.delegate = self
    splitViewController.preferredPrimaryColumnWidthFraction = 0.33
    splitViewController.minimumPrimaryColumnWidth = 375
    splitViewController.preferredDisplayMode = .allVisible

    return true

func splitViewController(_ splitViewController: UISplitViewController, collapseSecondary secondaryViewController:UIViewController, onto primaryViewController:UIViewController) -> Bool {
    return true

The reason for having this in the AppDelegate is I saw an example where placing it hear will allow me not to require the code in each of the different Master Views (each tab). Have yet to test this as still working on the first master view.

Master View

override func viewDidLoad()


    self.extendedLayoutIncludesOpaqueBars = true

    self.navigationItem.hidesBackButton = true

    // 3D Touch
    if traitCollection.forceTouchCapability == .available {
        registerForPreviewing(with: self as UIViewControllerPreviewingDelegate, sourceView: view)
        ThreeDTouch = true



func addSwitchVewButtonToNavigationBar() {
    let switchButton = UIButton(type: UIButtonType.custom)

    let editImage = UIImage(named: "CollectionButton")?.withRenderingMode(.alwaysTemplate)
    switchButton.setImage(editImage, for: .normal)
    switchButton.addTarget(self, action: #selector(SpeciesViewController.onSwitchView), for: UIControlEvents.touchUpInside)
    let switchButtonFinal = UIBarButtonItem(customView:switchButton)

    self.navigationItem.rightBarButtonItem = switchButtonFinal


@IBAction func onSwitchView(_ sender: UIBarButtonItem)
    AppDelegate.getAppState().isListViewSelected = false

    let speciesColletion = storyboard?.instantiateViewController(withIdentifier: Resource.SpeciesCollectionStoryboard) as! SpeciesCollectionViewController
    self.navigationController?.viewControllers = [speciesColletion]

Originally, the onSwitchViewButton was embedded using the IB, but did not work. This is the same system used for the addFavorite on the Detail View.

enter image description here
enter image description here

Get this bounty!!!

#StackBounty: #ios #swift #sirikit #ios-contacts iOS Contact app Interaction

Bounty: 50

I’m trying to get a messaging app integrated with the iOS Contacts app, so that users can initiate messages via the app directly from Contacts. This was covered in WWDC 2016 session 240 but apparently some details were omitted.

Following the WWDC example, I have:

  • Added the activity type to the app’s Info.plist:
  • Implemented application(_:continue:restorationHandler:) in my app delegate.

  • Created and donated an interaction
    let activity = NSUserActivity(activityType: "com.example.message")  
    activity.title = "Send CB Test Message"  
    activity.expirationDate = Date.distantFuture  
    let recipient = INPerson( /* recipient with an email address in my Contacts database */ )  
    let sender = INPerson( /* me */ )        
    let intent = INSendMessageIntent(recipients: [recipient], content: nil, groupName: nil, serviceName: "CB Test Chat", sender: sender)  
    let interaction = INInteraction(intent: intent, response: nil)  
    interaction.direction = .outgoing  
    interaction.donate { (error) in  
        if let error = error {  
            print("Donate error: (error)")  

This sort of works. The app shows up as an option on the one recipient’s card in Contacts. Tapping it in Contacts launches my app with an NSUserActivity. That’s good but it’s not enough.

The WWDC session used WhatsApp as an example. WhatsApp shows up as an option on all of my contacts, even those without WhatsApp accounts. I thought maybe WhatsApp had created and donated interactions for everyone. But if I create a new contact while WhatsApp isn’t running, it’s immediately an option on that contact. I experimented a little, setting the recipient argument to nil or to an empty array, but that had no effect.

So what am I missing here? I’m close, maybe? But it seems like donating interactions might not be what I actually need.

Get this bounty!!!

#StackBounty: #ios #swift #terrain #srtm #hgt Creating Terrain Map with SRTM HGT File

Bounty: 500

I am working on an iOS application. Where I show the Elevation and Topography map of a certain area. I have managed to download the .hgt file within app from here.

So far I am able to extract the Elevation from the hgt file. Now I have to also show the Terrain Map for that area. I have been searching about it and I think I can’t create terrain map directly with hgt file within iOS application. I have to use GRASS GIS, SRTM2OSM or TileMill to create terrain map and then use it in application.

Can please anyone direct me what I can do here and how to proceed.

Get this bounty!!!

#StackBounty: #swift #ios Create a view with a think inner border that has a gradient

Bounty: 50

InnerGradientBorderView is a subclass of UIView that has a thick border with a gradient. I have tried to replicate the Zoom meeting UI. They apply this kind of a border during screenshare.

import UIKit

class InnerGradientBorderView: UIView {

    var gradientLayers = [CAGradientLayer]()

    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = UIColor.clear

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        backgroundColor = UIColor.clear

    override func layoutSubviews() {

        for layer in gradientLayers {

        addGradientInnerBorder(width: 8, color: UIColor.orange)

    func addGradientInnerBorder(width: CGFloat, color: UIColor) {

        // Setup
        let topLeftO = CGPoint(x: 0, y: 0)
        let topLeftI = CGPoint(x: width, y: width)

        let topRightO = CGPoint(x: frame.width, y: 0)
        let topRightI = CGPoint(x: frame.width - width, y: width)

        let bottomLeftO = CGPoint(x: 0, y: frame.height)
        let bottomLeftI = CGPoint(x: width, y: frame.height - width)

        let bottomRightO = CGPoint(x: frame.width, y: frame.height)
        let bottomRightI = CGPoint(x: frame.width - width, y: frame.height - width)

        // Top
        let topPoints = [topLeftO, topLeftI, topRightI, topRightO, topLeftO]
        let topGradientPoints = [CGPoint(x: 0, y: 0), CGPoint(x: 0, y: 1)]
        gradientLayers.append(addGradientToBeizerPath(path: addClosedPathForPoints(points: topPoints), color: color, gradientPoints: topGradientPoints))

        // Left
        let leftPoints = [topLeftO, topLeftI, bottomLeftI, bottomLeftO, topLeftO]
        let leftGradientPoints = [CGPoint(x: 0, y: 0), CGPoint(x: 1, y: 0)]
        gradientLayers.append(addGradientToBeizerPath(path: addClosedPathForPoints(points: leftPoints), color: color, gradientPoints: leftGradientPoints))

        // Right
        let rightPoints = [topRightO, topRightI, bottomRightI, bottomRightO, topRightO]
        let rightGradientPoints = [CGPoint(x: 1, y: 0), CGPoint(x: 0, y: 0)]
        gradientLayers.append(addGradientToBeizerPath(path: addClosedPathForPoints(points: rightPoints), color: color, gradientPoints: rightGradientPoints))

        // Bottom
        let bottomPoints = [bottomLeftO, bottomLeftI, bottomRightI, bottomRightO, bottomLeftO]
        let bottomGradientPoints = [CGPoint(x: 0, y: 1), CGPoint(x: 0, y: 0)]
        gradientLayers.append(addGradientToBeizerPath(path: addClosedPathForPoints(points: bottomPoints), color: color, gradientPoints: bottomGradientPoints))

    func addClosedPathForPoints(points: [CGPoint]) -> UIBezierPath? {
        guard points.count == 5 else { return nil }

        let path = UIBezierPath()
        path.move(to: points[0])

        path.addLine(to: points[1])
        path.addLine(to: points[2])
        path.addLine(to: points[3])
        path.addLine(to: points[4])


        return path

    func addGradientToBeizerPath(path: UIBezierPath?, color: UIColor, gradientPoints: [CGPoint]) -> CAGradientLayer {
        guard let path = path, gradientPoints.count == 2 else { return CAGradientLayer() }

        let gradient = CAGradientLayer()
        gradient.frame = path.bounds
        gradient.bounds = path.bounds // This fixes the code.
        gradient.colors = [color.cgColor, UIColor.white.cgColor]
        gradient.startPoint = gradientPoints[0]
        gradient.endPoint = gradientPoints[1]

        let shapeMask = CAShapeLayer()
        shapeMask.path = path.cgPath
        gradient.mask = shapeMask

        self.layer.insertSublayer(gradient, at: 0)

        return gradient

Get this bounty!!!

#StackBounty: #ios #swift #wkwebview WKWebView on device can't load cached HTML

Bounty: 100

I have a WKWebView that works in Simulator perfectly but why runs in the device only a white empty screen appear this is my code:

override func loadView() {
    let webConfiguration = WKWebViewConfiguration()
    webConfiguration.preferences.setValue(true, forKey:"allowFileAccessFromFileURLs")
    webView = WKWebView(frame: .zero, configuration: webConfiguration)
    webView.uiDelegate = self
    view = webView

override func viewDidLoad() {

    let path2Esferas = Path.localPath.stringByAppendingPathComponent(path: "(Path.DIR_IMAGES)(ImagenDescargaTipo.esfera.rawValue)/(desarrollo.id)/virtualtour.html")
    let url =  URL(fileURLWithPath: path2Esferas) 
    //NSURL.fileURL(withPath: path2Esferas)

    let myRequest = URLRequest(url: url)

The HTML in “path2Esferas” is in a cache’s folder that I load previously, if I put a different URL like let myURL = URL(string: "https://www.apple.com") as docs show, it works correctly in simulator and device.

Get this bounty!!!

#StackBounty: #swift #xcode #ios11 #uitoolbar UIToolbars: different height thru code and designer

Bounty: 100

Can not find where I did a mistake in creating toolbars.

1 – was created thru code, please see below

let toolBar = UIToolbar()
var items = [UIBarButtonItem]()
toolBar.barTintColor = theme.barTintColor
let share = UIBarButtonItem(barButtonSystemItem: .action, target: nil, action: nil)         
items.append(UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil))
let trash = UIBarButtonItem(barButtonSystemItem: .trash, target: nil, action: nil)

toolBar.translatesAutoresizingMaskIntoConstraints = false

if #available(iOS 11.0, *) {           
   let guide = self.view.safeAreaLayoutGuide
   toolBar.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
   toolBar.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
   toolBar.bottomAnchor.constraint(equalTo: guide.bottomAnchor).isActive = true
  //toolBar.heightAnchor.constraint(equalToConstant: 44).isActive = true

2 – was added thru designer

looks like they have different height and as a result different indentation above the UIBarButtonItems


EDIT 0: In the storyboard, the toolbar 2 configured by default

enter image description here

EDIT 1: visual debugger shows the _UIToolbarContentView from toolbar 2 is higher then _UIToolbarContentView toolbar 1 on 5px.

<_UIToolbarContentView: 0x153e13190; frame = (0 0; 375 49); autoresize = W+H; layer = <CALayer: 0x1d0236d80>>
Printing description of $28:
<_UIToolbarContentView: 0x15b9f08d0; frame = (0 0; 375 44); autoresize = W+H; layer = <CALayer: 0x1d522af00>>

EDIT 2: This strange behavior on iPhone X, on iPhone 6 all fine.

enter image description here

Workaround: if iPhone X, add this hack
toolBar.heightAnchor.constraint(equalToConstant: 49)

Get this bounty!!!

#StackBounty: #ios #iphone #swift UITextView in custom inputaccessoryView not resigning first responder status

Bounty: 50

I have a chat application that implements a floating text input field (similar to the iOS Messages app) as the inputAccessoryView of my ChatViewController (see Apple’s documentation).

class ChatViewController: UIViewController {

    override var inputAccessoryView: UIView? {
       return chatInputView

    override var canBecomeFirstResponder: Bool {
        return true

My ChatViewController has a ChatTableViewController child view controller, which has cells containing UITextFields whose text content is editable. The issue I’m running into is that when the user taps on a cell’s UITextField, the inputAccessoryView‘s UITextView refuses to resign first responder status, which prevents the content in the UITableViewCell from being edited. The following warning is logged in the console:

 First responder warning: '<UITextView: 0x7fc041041c00; 
 frame = ...' rejected resignFirstResponder when being removed from hierarchy

I’ve tried calling resignFirstResponder and endEditing on the UIInputView and UITextView directly with no success. I don’t want the ChatViewController to resign first responder status as that would cause the inputAccessoryView to disappear.

Get this bounty!!!

#StackBounty: #ios #swift #arkit How can I set text orientation in ARKit?

Bounty: 250

I am creating a simple app with ARKit in which I add some text to the scene to the tapped position:

@objc func tapped(sender: UITapGestureRecognizer){
    let sceneView = sender.view as! ARSCNView
    let tapLocation = sender.location(in: sceneView)
    let hitTest = sceneView.hitTest(tapLocation, types: .featurePoint)
    if !hitTest.isEmpty{
        self.addTag(tag: "A", hitTestResult: hitTest.first!)
        print("no match")

func addTag(tag: String, hitTestResult: ARHitTestResult){
    let tag = SCNText(string:tag, extrusionDepth: 0.1)
    tag.font = UIFont(name: "Optima", size: 1)
    tag.firstMaterial?.diffuse.contents = UIColor.red

    let tagNode = SCNNode(geometry: tag)

    let transform = hitTestResult.worldTransform
    let thirdColumn = transform.columns.3
    tagNode.position = SCNVector3(thirdColumn.x,thirdColumn.y - tagNode.boundingBox.max.y / 2,thirdColumn.z)
    print("(thirdColumn.x) (thirdColumn.y) (thirdColumn.z)")

It works, but I have problem with the orientation of the text. When I add it with the camera’s original position, the text orientation is ok, I can see the text frontwise (Sample 1). But when I turn camera to the left / right, and add the text by tapping, I can see the added text from the side (Sample 2).

Sample 1:

3-D letter from the front

Sample 2:

3-D letter from the side

I know there should be some simple trick to solve it, but as a beginner in this topic I could not find it so far.

Get this bounty!!!