Push UITableView down when adding subview to UINavigationBar - swift

I'm trying to implement a notification bar which should appear below the UINavigationBar. The problem is that when the notification appears the cells in the UITableView are not pushed down and are therefore hidden behind the notification like this:
My code looks as follows:
#IBOutlet var notificationView: UIView!
let navBar = self.navigationController?.navigationBar
let navBarHeight = navBar?.frame.height
let notificationFrame = notificationView.frame
let nSetX = notificationFrame.origin.x
let nSetY = CGFloat(navBarHeight!)
let nSetWidth = self.view.frame.width
let nSetHight = notificationFrame.height
notificationView.frame = CGRect(x: nSetX, y: nSetY, width: nSetWidth, height: nSetHight)
self.navigationController?.navigationBar.addSubview(notificationView)

There are a few solutions for your problem, but maybe the easiest one for you could be adding a content offset on the top, like this:
self.tableView.contentInset = UIEdgeInsetsMake(newBar.height, 0, 0, 0)
Another solution as #h44f33z suggested is adding a constraint between the new bar and the tableView, so it would be similar to this (in visual format):
"V:|-0-[newBar(\(newBar.height))]-0-[tableView]-0-|"

Related

NSToolbar Flexible space not working in Swift 5.x

I developed this app using Xcode 10.1 (Swift 4.2 I believe) and toolbar looks good:
But I ported in over to my Xcode 11.6 (Swift 5.2 I believe), now the right-most item on the toolbar is no longer on the far right:
Before the port, I added that plus button - the checkbox (Show Hidden) was one of the first items and was never changed since.
Also the buttons function as expected - their actions fire OK.
Note: This app uses no Storyboards or IB things.
Since my code in split over several files (with lots of unrelated code), I will give an overview.
class ToolbarController: NSObject, NSToolbarDelegate {
let toolbar = NSToolbar(identifier: NSToolbar.Identifier("toolbar"))
lazy var toolbarItem1: NSToolbarItem = {
let toolbarItem = NSToolbarItem(itemIdentifier: NSToolbarItem.Identifier(rawValue: "Btn1"))
let button = NSButton(frame: NSRect(x: 0, y: 0, width: 40, height: 1))
button.target = self
...
toolbarItem.view = button
return toolbarItem
}() // defined as "lazy" to allow "self"
var toolbarItemSpace: NSToolbarItem = {
let toolbarItem = NSToolbarItem(itemIdentifier: NSToolbarItem.Identifier.space)
return toolbarItem
}()
...
var toolbarItemFlexSpace: NSToolbarItem = {
let toolbarItem = NSToolbarItem(itemIdentifier: NSToolbarItem.Identifier.flexibleSpace)
return toolbarItem
}()
lazy var toolbarItemShowHidden: NSToolbarItem = {
let toolbarItem = NSToolbarItem(itemIdentifier: NSToolbarItem.Identifier(rawValue: "Checkbox"))
let box = NSBox(frame: NSRect(x: 0, y: 0, width: 120, height: 40))
let button = NSButton() // put in NSBox to use isolated action
...
button.target = self
box.contentView = button
box.sizeToFit() // tightly fit the contents (button)
toolbarItem.view = box
return toolbarItem
}()
lazy var tbItems: [NSToolbarItem] = [toolbarItem1, ...]
That class defines the toolbar, add the items, implements all those toolbar (delegate) methods and makes it the delegate. My NSWindowController then set it to the application toolbar.
Can anyone see an issue with my code that causes the above?
Otherwise, is this a bug?
Had the same problem with Swift 5.0 ... even though the documentation says minSize and maxSize are deprecated, I solved this like:
let toolbarItem = NSToolbarItem(itemIdentifier: NSToolbarItem.Identifier.flexibleSpace)
toolbarItem.minSize = NSSize(width: 1, height: 1)
toolbarItem.maxSize = NSSize(width: 1000, height: 1) //just some large value
return toolbarItem
Maybe this works as well for Swift 5.2
Found a way without living w/ the warning & not using the deprecated properties.
We create a transparent subview for the NASToolbarItem with the min / max constraints in advance, so the system has a way to calc the min and max size itself.
let toolbarItem = NSToolbarItem(itemIdentifier: NSToolbarItem.Identifier.flexibleSpace)
// view to be hosted in the flexible space toolbar item
let view = NSView(frame: CGRect(origin: .zero, size: CGSize(width: MIN_TOOLBAR_ITEM_W, height: MIN_TOOLBAR_H)))
view.widthAnchor.constraint(lessThanOrEqualToConstant: MAX_TOOLBAR_ITEM_W).isActive = true
view.widthAnchor.constraint(greaterThanOrEqualToConstant: MIN_TOOLBAR_ITEM_W).isActive = true
// set the view and return
toolbarItem?.view = view
return toolbarItem

NSAlert with NSTableview in it size issues

I have an NSAlert and I set its accessoryView to be an NSTableView. It works good with small-medium amounts of data, but when the row count is getting large, the tableview resizes instead of getting a scrollbar.
I would expect the table to only take up as much space as I give it in the Init frame.
var alert = NSAlert()
var sampleTable = NSTableView(frame: NSRect(x: 0, y:0, width: 400, height:400))
sampleTable.dataSource = self
alert.accessoryView = sampleTable
alert.beginSheetModal(...) // irrelevant code from here on
Set the scrolliew.autohidesScrollers = false and scrollView.hasHorizontalScroller = true where scrollView is an NSScrollView instance

Set position of nspopover

I have a view controller (A), which will show another viewcontroller (B) as a popover.
In my VC (A) is an NSButton with this IBAction:
self.presentViewController(vcPopover, asPopoverRelativeTo: myButton.bounds, of: myButton, preferredEdge: .maxX, behavior: .semitransient)
The result:
now I would like to change the position of my popover - I would like to move it up.
I tried this:
let position = NSRect(origin: CGPoint(x: 100.0, y: 120.0), size: CGSize(width: 0.0, height: 0.0))
self.presentViewController(vcPopover, asPopoverRelativeTo: position, of: myButton, preferredEdge: .maxX, behavior: .semitransient)
But the position does not change
ANOTHER EXAMPLE
I have a segmented control. If you click on segment "1" a popover will be shown (same code like above). But the arrow pointed to segment "2" instead to segment "1"
First, ensure your popover is really an NSPopover and not simply an NSViewController. Assuming the view controller you want to wrap in the popover has a storyboard id of "vcPopover", getting the content vc would look like:
let popoverContentController = NSStoryboard(name: NSStoryboard.Name(rawValue: "Main"), bundle: nil).instantiateController(withIdentifier: NSStoryboard.SceneIdentifier(rawValue: "vcPopover")) as! NSViewController
Then, wrap it in a popover:
let popover = NSPopover()
popover.contentSize = NSSize(width: 200, height: 200) // Or whatever size you want, perhaps based on the size of the content controller
popover.behavior = .semitransient
popover.animates = true
popover.contentViewController = popoverContentController
Then, to present, call show(relativeTo:of:preferredEdge:):
vcPopover.show(relativeTo: myButton.bounds, of: myButton, preferredEdge: .maxX)
This should update the position of the popover.
Update: You are likely using an NSSegmentedControl, which means you need to pay special attention to the rect you pass in show. You need to pass a bounds rect within the segmented control's coordinate system that describes the area of the segment. Here's a detailed example:
// The view controller doing the presenting
class ViewController: NSViewController {
...
var presentedPopover: NSPopover?
#IBAction func selectionChanged(_ sender: NSSegmentedControl) {
let segment = sender.selectedSegment
if let storyboard = storyboard {
let contentVC = storyboard.instantiateController(withIdentifier: NSStoryboard.SceneIdentifier("vcPopover")) as! NSViewController
presentedPopover = NSPopover()
presentedPopover?.contentSize = NSSize(width: 200, height: 200)
presentedPopover?.behavior = .semitransient
presentedPopover?.animates = true
presentedPopover?.contentViewController = contentVC
}
presentedPopover?.show(relativeTo: sender.relativeBounds(forSegment: segment), of: sender, preferredEdge: .minY)
}
}
extension NSSegmentedControl {
func relativeBounds(forSegment index: Int) -> NSRect {
// Assuming equal widths
let segmentWidth = bounds.width / CGFloat(segmentCount)
var rect = bounds
rect.size.width = segmentWidth
rect.origin.x = rect.origin.x + segmentWidth * CGFloat(index)
return rect
}
}
Notice that the extension to NSSegmentedControl calculates an approximate rectangle for the segment using the width. This method assumes equal widths and does not account for borders. You may modify this method to account for what you need. Information about getting the frame of a segment for iOS (which is similar) can be found here.
This example is verified as working correctly as long as a view controller exists in the same storyboard with a storyboard identifier of "vcPopover".

SystemStatusBar statusItem title being cut short on OS X

I am trying to display an OS X application statusItem in the System Status Bar and am having success with everything except the fact that the title is being cut off. I am initializing everything like so:
let statusItem = NSStatusBar.systemStatusBar().statusItemWithLength(-1)
func applicationDidFinishLaunching(aNotification: NSNotification) {
let icon = NSImage(named: "statusIcon")
icon?.template = true
statusItem.image = icon
statusItem.menu = statusMenu
statusItem.title = "This is a test title"
}
The problem is the statusItem.title is appearing like so:
As you can see the application next to mine (iStatMenuBar) is cutting off the title to my application (or something similar is happening)
If I comment out the icon for the statusItem, it works and shows the entire title but when I re-add the icon it cuts off again. Is there a way for the two (icon and title) to co exist? I have reviewed some Apple docs and may have missed a critical piece which explains this.
Thanks guys.
One option would be to assign a custom view to your statusBarItem and within that view's class override drawRect(dirtyRect: NSRect) e.g.
private var icon:StatusMenuView?
let bar = NSStatusBar.systemStatusBar()
item = bar.statusItemWithLength(-1)
self.icon = StatusMenuView()
item!.view = icon
and StatusMenuView might look like:
// This is an edited copy & paste from one of my personal projects so it might be missing some code
class StatusMenuView:NSView {
private(set) var image: NSImage
private let titleString:NSString = "really long title..."
init() {
icon = NSImage(named: "someImage")!
let myWideStatusBarItemFrame = CGRectMake(0, 0, 180.0, NSStatusBar.systemStatusBar().thickness)
super.init(frame.rect)
}
override func drawRect(dirtyRect: NSRect)
{
self.item.drawStatusBarBackgroundInRect(dirtyRect, withHighlight: self.isSelected)
let size = self.image.size
let rect = CGRectMake(2, 2, size.width, size.height)
self.image.drawInRect(rect)
let titleRect = CGRectMake( 2 + size.width, dirtyRect.origin.y, 180.0 - size.width, size.height)
self.titleString.drawInRect(titleRect, withAttributes: nil)
}
}
Now, the above might change your event handling, you'll need to handle mouseDown in the StatusMenuView class.

How to update UILabel that is a subview of inputView?

I have UITextView where user types a text. When the keyboard is shown, I add inputView with UIlabel on it. I want this UIlabel to hold character length of the text. It seems very easy task, but unfortunatelly it does not update this word counter UILabel when user change text..
this is how I load the inputView
_textView.inputView = [self inputAccessoryView];
in inputAccessoryView I simply add UILabel as a subview. When keyboard is show, UILabel is also show with inputView. I track changes on
- (void)textViewDidChange:(UITextView *)textView
unfortunatelly the UILabel is never updated (redrawn). When I log in to console its value, the value is correct, so its updating, but the UIlabel is never redrawn and holds the default value.
Can anyone help me with this?
did you
_textView.delegate = self;
?
I know it was 5 years ago, but it might help others, who like me stumble upon your question.
I use a UIToolbar as my inputAccessoryView (in my case it has a label, a flexible separator and a button).
On textFieldEditingChanged event I rebuild part of the toolbar like this
#IBAction func textFieldEditingChanged(_ sender: UITextField) {
//get a reference to the toolbar
let toolBar = sender.inputAccessoryView as! UIToolbar
//create a new label and set size + other properties
toolbarLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 40, height: 22))
toolbarLabel.text = mySpecificCalculatedString(sender.text!)
toolbarLabel.font = defaultFont(17)
toolbarLabel.adjustsFontSizeToFitWidth = true
let width = toolbarLabel.textRect(forBounds: CGRect(x: 0, y: 0, width: maxWidthForLabel, height: 0), limitedToNumberOfLines: 1).size.width
toolbarLabel.frame = CGRect(x: 0, y: 0, width: width, height: 22)
toolbarLabel.textColor = .black
toolbarLabel.tag = 666
//rebuild the specific tolbar item
let customView = UIBarButtonItem(customView: toolbarLabel)
toolBar.items![0] = customView
}
Note: simply changing the text of the label did not work for me either, I had to reinitialize it.
Hope it helps.