Using interface builder you can select the corners an object should stick to when resizing. How can you do this programatically?
I find that the autoresizingBit masks are horribly named, so I use a category on NSView to make things a little more explicit:
// MyNSViewCategory.h:
#interface NSView (myCustomMethods)
- (void)fixLeftEdge:(BOOL)fixed;
- (void)fixRightEdge:(BOOL)fixed;
- (void)fixTopEdge:(BOOL)fixed;
- (void)fixBottomEdge:(BOOL)fixed;
- (void)fixWidth:(BOOL)fixed;
- (void)fixHeight:(BOOL)fixed;
#end
// MyNSViewCategory.m:
#implementation NSView (myCustomMethods)
- (void)setAutoresizingBit:(unsigned int)bitMask toValue:(BOOL)set
{
if (set)
{ [self setAutoresizingMask:([self autoresizingMask] | bitMask)]; }
else
{ [self setAutoresizingMask:([self autoresizingMask] & ~bitMask)]; }
}
- (void)fixLeftEdge:(BOOL)fixed
{ [self setAutoresizingBit:NSViewMinXMargin toValue:!fixed]; }
- (void)fixRightEdge:(BOOL)fixed
{ [self setAutoresizingBit:NSViewMaxXMargin toValue:!fixed]; }
- (void)fixTopEdge:(BOOL)fixed
{ [self setAutoresizingBit:NSViewMinYMargin toValue:!fixed]; }
- (void)fixBottomEdge:(BOOL)fixed
{ [self setAutoresizingBit:NSViewMaxYMargin toValue:!fixed]; }
- (void)fixWidth:(BOOL)fixed
{ [self setAutoresizingBit:NSViewWidthSizable toValue:!fixed]; }
- (void)fixHeight:(BOOL)fixed
{ [self setAutoresizingBit:NSViewHeightSizable toValue:!fixed]; }
#end
Which can then be used as follows:
[someView fixLeftEdge:YES];
[someView fixTopEdge:YES];
[someView fixWidth:NO];
See the setAutoresizingMask: method of NSView and the associated resizing masks.
Each view has the mask of flags, controlled by setting a the autoresizingMask property with the OR of the behaviors you want from the resizing masks. In addition, the superview needs to be configured to resize its subviews.
Finally, in addition to the basic mask-defined resizing options, you can fully control the layout of subviews by implementing -resizeSubviewsWithOldSize:
#e.James answer gave me an idea to simply create a new enum with more familiar naming:
typedef NS_OPTIONS(NSUInteger, NSViewAutoresizing) {
NSViewAutoresizingNone = NSViewNotSizable,
NSViewAutoresizingFlexibleLeftMargin = NSViewMinXMargin,
NSViewAutoresizingFlexibleWidth = NSViewWidthSizable,
NSViewAutoresizingFlexibleRightMargin = NSViewMaxXMargin,
NSViewAutoresizingFlexibleTopMargin = NSViewMaxYMargin,
NSViewAutoresizingFlexibleHeight = NSViewHeightSizable,
NSViewAutoresizingFlexibleBottomMargin = NSViewMinYMargin
};
Also, from my research, I discovered that #James.s has a serious bug in the NSView additions. The coordinate system in Cocoa has a flipped y-axis in terms of iOS coordinates system. Hence, in order to fix the bottom and top margin, you should write:
- (void)fixTopEdge:(BOOL)fixed
{ [self setAutoresizingBit:NSViewMaxYMargin toValue:!fixed]; }
- (void)fixBottomEdge:(BOOL)fixed
{ [self setAutoresizingBit:NSViewMinYMargin toValue:!fixed]; }
From the cocoa docs:
NSViewMinYMargin
The bottom margin between the receiver and its superview is flexible.
Available in OS X v10.0 and later.
Related
UIScrollView has an excellent contentInset property which tells the view, which portion is visible on the screen. I have an MKMapView which is partially covered by a translucent view. I want the map to be visible under the view. I have to display several annotations on the map, and I want to zoom to them using -setRegion:animated:, but the map view does not respect that it is partially covered, therefore some of my annotations will be covered by the translucent view.
Is there any way to tell the map, to calculate like the scroll view does using contentInset?
UPDATE: This is what I've tried:
- (MKMapRect)mapRectForAnnotations
{
if (self.trafik) {
MKMapPoint point = MKMapPointForCoordinate(self.trafik.coordinate);
MKMapPoint deltaPoint;
if (self.map.userLocation &&
self.map.userLocation.coordinate.longitude != 0) {
MKCoordinateSpan delta = MKCoordinateSpanMake(fabsf(self.trafik.coordinate.latitude-self.map.userLocation.coordinate.latitude),
fabsf(self.trafik.coordinate.longitude-self.map.userLocation.coordinate.longitude));
deltaPoint = MKMapPointForCoordinate(CLLocationCoordinate2DMake(delta.latitudeDelta, delta.longitudeDelta));
} else {
deltaPoint = MKMapPointForCoordinate(CLLocationCoordinate2DMake(0.01, 0.01));
}
return MKMapRectMake(point.x, point.y, deltaPoint.x, deltaPoint.y);
} else {
return MKMapRectNull;
}
}
Use UIViews's layoutMargins.
E.g. This will force the current user's position pin to move 50pts up.
mapView.layoutMargins = UIEdgeInsets(top: 0.0, left: 0.0, bottom: 100.0, right: 0.0)
You can do the following but it could mess with other views in your UIViewController that use bottomLayoutGuide. You'll have to test it to find out.
Override bottomLayoutGuide in the UIViewController that has your map as a subview and return a MyLayoutGuide object that looks like:
#interface MyLayoutGuide : NSObject <UILayoutSupport>
#property (nonatomic) CGFloat length;
-(id)initWithLength:(CGFloat)length;
#end
#implementation MyLayoutGuide
#synthesize length = _length;
#synthesize topAnchor = _topAnchor;
#synthesize bottomAnchor = _bottomAnchor;
#synthesize heightAnchor = _heightAnchor;
- (id)initWithLength:(CGFloat)length
{
if (self = [super init]) {
_length = length;
}
return self;
}
#end
bottomLayoutGuide that insets the MKMapView by 50 points:
- (id)bottomLayoutGuide
{
CGFloat bottomLayoutGuideLength = 50.f;
return [[MyLayoutGuide alloc] initWithLength:bottomLayoutGuideLength];
}
You can force this "inset" to be calculated again by calling setNeedsLayout on your MKMapView in the event that your time table on the bottom changes size. We've created a helper in our MKMapView subclass that can be called from the parent UIViewController:
- (void)updateBottomLayoutGuides
{
// this method ends up calling -(id)bottomLayoutGuide on its UIViewController
// and thus updating where the Legal link on the map should be.
[self.mapView setNeedsLayout];
}
Answer adapted from this answer.
I have a custom NSView subclass which has a border around itself. The border is drawn inside this view. Is it possible to respect this borders with auto layout?
For example, when I place the subview to my custom view and set constraints like this:
#"H:|-(myViewSubView)-|" (not #"H:|-(myViewBorderWidth)-(myViewSubView)-(myViewBorderWidth)-|")
#"V:|-(myViewSubView)-|"
the layout must be:
Horizontal: |-(myViewBorderWidth)-|myViewSubview|-(myViewBorderWidth)-|
Vertical: |-(myViewBorderWidth)-|myViewSubview|-(myViewBorderWidth)-|
I've tried to overwrite -bounds method in my view to return the bounds rect without the borders, but it doesn't help.
UPDATE
I just noticed that your question is talking about NSView (OS X), not UIView (iOS). Well, this idea should still be applicable, but you won't be able to drop my code into your project unchanged. Sorry.
ORIGINAL
Consider changing your view hierarchy. Let's say your custom bordered view is called BorderView. Right now you're adding subviews directly to BorderView and creating constraints between the BorderView and its subviews.
Instead, give the BorderView a single subview, which it exposes in its contentView property. Add your subviews to the contentView instead of directly to the BorderView. Then the BorderView can lay out its contentView however it needs to. This is how UITableViewCell works.
Here's an example:
#interface BorderView : UIView
#property (nonatomic, strong) IBOutlet UIView *contentView;
#property (nonatomic) UIEdgeInsets borderSize;
#end
If we're using a xib, then we have the problem that IB doesn't know that it should add subviews to the contentView instead of directly to the BorderView. (It does know this for UITableViewCell.) To work around that, I've made contentView an outlet. That way, we can create a separate, top-level view to use as the content view, and connect it to the BorderView's contentView outlet.
To implement BorderView this way, we'll need an instance variable for each of the four constraints between the BorderView and its contentView:
#implementation BorderView {
NSLayoutConstraint *topConstraint;
NSLayoutConstraint *leftConstraint;
NSLayoutConstraint *bottomConstraint;
NSLayoutConstraint *rightConstraint;
UIView *_contentView;
}
The contentView accessor can create the content view on demand:
#pragma mark - Public API
- (UIView *)contentView {
if (!_contentView) {
[self createContentView];
}
return _contentView;
}
And the setter can replace an existing content view, if there is one:
- (void)setContentView:(UIView *)contentView {
if (_contentView) {
[self destroyContentView];
}
_contentView = contentView;
[self addSubview:contentView];
}
The borderSize setter needs to arrange for the constraints to be updated and for the border to be redrawn:
- (void)setBorderSize:(UIEdgeInsets)borderSize {
if (!UIEdgeInsetsEqualToEdgeInsets(borderSize, _borderSize)) {
_borderSize = borderSize;
[self setNeedsUpdateConstraints];
[self setNeedsDisplay];
}
}
We'll need to draw the border in drawRect:. I'll just fill it with red:
- (void)drawRect:(CGRect)rect {
CGRect bounds = self.bounds;
UIBezierPath *path = [UIBezierPath bezierPathWithRect:bounds];
[path appendPath:[UIBezierPath bezierPathWithRect:UIEdgeInsetsInsetRect(bounds, self.borderSize)]];
path.usesEvenOddFillRule = YES;
[path addClip];
[[UIColor redColor] setFill];
UIRectFill(bounds);
}
Creating the content view is trivial:
- (void)createContentView {
_contentView = [[UIView alloc] init];
[self addSubview:_contentView];
}
Destroying it is slightly more involved:
- (void)destroyContentView {
[_contentView removeFromSuperview];
_contentView = nil;
[self removeConstraint:topConstraint];
topConstraint = nil;
[self removeConstraint:leftConstraint];
leftConstraint = nil;
[self removeConstraint:bottomConstraint];
bottomConstraint = nil;
[self removeConstraint:rightConstraint];
rightConstraint = nil;
}
The system will automatically call updateConstraints before doing layout and drawing if somebody has called setNeedsUpdateConstraints, which we did in setBorderSize:. In updateConstraints, we'll create the constraints if necessary, and update their constants based on borderSize. We also tell the system not to translate the autoresizing masks into constraints, because that tends to create unsatisfiable constraints.
- (void)updateConstraints {
self.translatesAutoresizingMaskIntoConstraints = NO;
self.contentView.translatesAutoresizingMaskIntoConstraints = NO;
[super updateConstraints];
if (!topConstraint) {
[self createContentViewConstraints];
}
topConstraint.constant = _borderSize.top;
leftConstraint.constant = _borderSize.left;
bottomConstraint.constant = -_borderSize.bottom;
rightConstraint.constant = -_borderSize.right;
}
All four constraints are created the same way, so we'll use a helper method:
- (void)createContentViewConstraints {
topConstraint = [self constrainContentViewAttribute:NSLayoutAttributeTop];
leftConstraint = [self constrainContentViewAttribute:NSLayoutAttributeLeft];
bottomConstraint = [self constrainContentViewAttribute:NSLayoutAttributeBottom];
rightConstraint = [self constrainContentViewAttribute:NSLayoutAttributeRight];
}
- (NSLayoutConstraint *)constrainContentViewAttribute:(NSLayoutAttribute)attribute {
NSLayoutConstraint *constraint = [NSLayoutConstraint constraintWithItem:_contentView attribute:attribute relatedBy:NSLayoutRelationEqual toItem:self attribute:attribute multiplier:1 constant:0];
[self addConstraint:constraint];
return constraint;
}
#end
I have put a complete working example in this git repository.
For future reference, you can override NSView.alignmentRectInsets to affect the position of the layout guides:
Custom views that draw ornamentation around their content can override
this property and return insets that align with the edges of the
content, excluding the ornamentation. This allows the constraint-based
layout system to align views based on their content, rather than just
their frame.
Link to documentation:
https://developer.apple.com/documentation/appkit/nsview/1526870-alignmentrectinsets
Have you tried setting the intrinsic size to include the border size?
- (NSSize)intrinsicContentSize
{
return NSMakeSize(width+bordersize, height+bordersize);
}
then you would set the content compression resistance priorities in both directions to be required:
[self setContentCompressionResistancePriority:NSLayoutPriorityRequired forOrientation:NSLayoutConstraintHorizontal];
[self setContentCompressionResistancePriority:NSLayoutPriorityRequired forOrientation:NSLayoutConstraintVertical];
The one solution I found is to overload the addConstraint: method and modify constraints before they'll be added:
- (void)addConstraint:(NSLayoutConstraint *)constraint
{
if(constraint.firstItem == self || constraint.secondItem == self) {
if(constraint.firstAttribute == NSLayoutAttributeLeading) {
constraint.constant += self.leftBorderWidth;
} else if (constraint.firstAttribute == NSLayoutAttributeTrailing) {
constraint.constant += self.rightBorderWidth;
} else if (constraint.firstAttribute == NSLayoutAttributeTop) {
constraint.constant += self.topBorderWidth;
} else if (constraint.firstAttribute == NSLayoutAttributeBottom) {
constraint.constant += self.bottomBorderWidth;
}
}
[super addConstraint:constraint];
}
And then also handle this constraints in xxxBorderWidth setters.
Like the iBooks app, when you pull down the tableview, a search bar and segmented control appear, to allow you to search and switch between two types of views.
It sticks in that position when you pull down far enough, and alternatively, gets hidden when you pull the tableview up enough.
I am trying to implement the same thing with a UISegmentedControl.
So far I have added a segmented control successfully as a subview to the table. (It has a negative Y frame so make it stick above the tableview).
I have also implemented this code:
- (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView {
float yOffset = scrollView.contentOffset.y;
if (yOffset < -70) {
[scrollView setContentOffset:CGPointMake(0.0f, -70.0f) animated:YES];
} else if (yOffset > -10) {
[scrollView setContentOffset:CGPointMake(0.0f, -11.0f) animated:YES];
}
}
This works great, until I try using the segmented control. Where the table will just act like it is scrolling, ignoring the segmented control altogether (i.e. if I tap on a segment, it doesn't even get selected, instead the table scrolls up, hiding the segmented control.
I did use the scrollViewDidScroll method but this made it buggy and the scrolling jumpy.
I also tried to make the segmented control's exclusiveTouch = YES, but this had no effect whatsoever.
I would be thankful for all help! thanks in advance!
Here is my code which works:
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
//
// Table view
//
if ([scrollView isKindOfClass:[myTableView class]]) {
//
// Discover top
//
CGFloat topY = scrollView.contentOffset.y + scrollView.contentInset.top;
if (topY <= self.tableHeaderHeightConstraint.constant) {
[self setIsScrolledToTop:YES];
} else {
[self setIsScrolledToTop:NO];
}
}
}
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
//
// Table view
//
if ([scrollView isKindOfClass:[myTableView class]]) {
//
// Toggle favourite category
//
if ([self isScrolledToTop]) {
//
// Show
//
} else {
//
// Hide
//
}
}
}
Edited the above code to make it a bit more generic, but syntactically its correct
I'm using a textured window that has a tab bar along the top of it, just below the title bar.
I've used -setContentBorderThickness:forEdge: on the window to make the gradient look right, and to make sure sheets slide out from the right position.
What's not working however, is dragging the window around. It works if I click and drag the area that's actually the title bar, but since the title bar gradient spills into a (potentially/often empty) tab bar, it's really easy to click too low and it feels really frustrating when you try to drag and realise the window is not moving.
I notice NSToolbar, while occupying roughly the same amount of space below the title bar, allows the window to be dragged around when the cursor is over it. How does one implement this?
Thanks.
I tried the mouseDownCanMoveWindow solution (https://stackoverflow.com/a/4564146/901641) but it didn't work for me. I got rid of that method and instead added this to my window subclass:
- (BOOL)isMovableByWindowBackground {
return YES;
}
which worked like a charm.
I found this here:
-(void)mouseDown:(NSEvent *)theEvent {
NSRect windowFrame = [[self window] frame];
initialLocation = [NSEvent mouseLocation];
initialLocation.x -= windowFrame.origin.x;
initialLocation.y -= windowFrame.origin.y;
}
- (void)mouseDragged:(NSEvent *)theEvent {
NSPoint currentLocation;
NSPoint newOrigin;
NSRect screenFrame = [[NSScreen mainScreen] frame];
NSRect windowFrame = [self frame];
currentLocation = [NSEvent mouseLocation];
newOrigin.x = currentLocation.x - initialLocation.x;
newOrigin.y = currentLocation.y - initialLocation.y;
// Don't let window get dragged up under the menu bar
if( (newOrigin.y+windowFrame.size.height) > (screenFrame.origin.y+screenFrame.size.height) ){
newOrigin.y=screenFrame.origin.y + (screenFrame.size.height-windowFrame.size.height);
}
//go ahead and move the window to the new location
[[self window] setFrameOrigin:newOrigin];
}
It works fine, though I'm not 100% sure I'm doing it correctly. There's one bug I've found so far, and that's if the drag begins inside a subview (a tab itself) and then enters the superview (the tab bar). The window jumps around. Some -hitTest: magic, or possibly even just invalidating initialLocation on mouseUp should probably fix that.
As of macOS 10.11, the simplest way to do this is to utilize the new -[NSWindow performWindowDragWithEvent:] method:
#interface MyView () {
BOOL movingWindow;
}
#end
#implementation MyView
...
- (BOOL)mouseDownCanMoveWindow
{
return NO;
}
- (void)mouseDown:(NSEvent *)event
{
movingWindow = NO;
CGPoint point = [self convertPoint:event.locationInWindow
fromView:nil];
// The area in your view where you want the window to move:
CGRect movableRect = CGRectMake(0, 0, 100, 100);
if (self.window.movableByWindowBackground &&
CGRectContainsPoint(movableRect, point)) {
[self.window performWindowDragWithEvent:event];
movingWindow = YES;
return;
}
// Handle the -mouseDown: as usual
}
- (void)mouseDragged:(NSEvent *)event
{
if (movingWindow) return;
// Handle the -mouseDragged: as usual
}
#end
Here, -performWindowDragWithEvent: will handle the correct behavior of not overlapping the menu bar, and will also snap to edges on macOS 10.12 and later. Be sure to include a BOOL movingWindow instance variable with your view's private interface so you can avoid -mouseDragged: events once you determined you don't want to process them.
Here, we are also checking that -[NSWindow movableByWindowBackground] is set to YES so that this view can be used in non-movable-by-window-background windows, but that is optional.
Have you tried overriding the NSView method mouseDownCanMoveWindow to return YES?
It works for me after TWO steps:
Subclass NSView, override the mouseDownCanMoveWindow to return YES.
Subclass NSWindow, override the isMovableByWindowBackground to return YES.
It's quite easy:
override mouseDownCanMoveWindow property
override var mouseDownCanMoveWindow:Bool {
return false
}
If you got a NSTableView in your window, with selection enabled, overriding the mouseDownCanMoveWindow property won't work.
You need instead to create a NSTableView subclass and override the following mouse events (and use the performWindowDragWithEvent: mentioned in Dimitri answer):
#interface WindowDraggableTableView : NSTableView
#end
#implementation WindowDraggableTableView
{
BOOL _draggingWindow;
NSEvent *_mouseDownEvent;
}
- (void)mouseDown:(NSEvent *)event
{
if (self.window.movableByWindowBackground == NO) {
[super mouseDown:event]; // Normal behavior.
return;
}
_draggingWindow = NO;
_mouseDownEvent = event;
}
- (void)mouseDragged:(NSEvent *)event
{
if (self.window.movableByWindowBackground == NO) {
[super mouseDragged:event]; // Normal behavior.
return;
}
assert(_mouseDownEvent);
_draggingWindow = YES;
[self.window performWindowDragWithEvent:_mouseDownEvent];
}
- (void)mouseUp:(NSEvent *)event
{
if (self.window.movableByWindowBackground == NO) {
[super mouseUp:event]; // Normal behavior.
return;
}
if (_draggingWindow == YES) {
_draggingWindow = NO;
return; // Event already handled by `performWindowDragWithEvent`.
}
// Triggers regular table selection.
NSPoint locationInWindow = event.locationInWindow;
NSPoint locationInTable = [self convertPoint:locationInWindow fromView:nil];
NSInteger row = [self rowAtPoint:locationInTable];
if (row >= 0 && [self.delegate tableView:self shouldSelectRow:row])
{
NSIndexSet *rowIndex = [NSIndexSet indexSetWithIndex:row];
[self selectRowIndexes:rowIndex byExtendingSelection:NO];
}
}
#end
Also don't forget to set the corresponding window movableByWindowBackground property as well:
self.window.movableByWindowBackground = YES;
When you set property isMovableByWindowBackground in viewDidLoad, it may not work because the window property of the view is not yet set. In that case, try this:
override func viewDidAppear() {
self.view.window?.isMovableByWindowBackground = true
}
Thank you! Dimitris' answer solved my issue but I needed it in swift 5. Here is what I came up with.
final class BlahField: NSTextView {
var movingWindow = false
override func mouseDown(with event: NSEvent) {
movingWindow = false
let point = self.convert(event.locationInWindow, from: nil)
if (self.window!.isMovableByWindowBackground && self.frame.contains(point)) {
self.window?.performDrag(with: event)
movingWindow = true
return
}
}
override func mouseDragged(with event: NSEvent) {
if (movingWindow) {
return
}
}
}
I have a text field with a background but to make it look right the text field needs to have some padding on the left side of it a bit like the NSSearchField does. How would I give the text field some padding on the left?
smorgan's answer points us in the right direction, but it took me quite a while to figure out how to restore the customized textfield's ability to display a background color -- you must call setBorder:YES on the custom cell.
This is too late to help Joshua, but here's the how you implement the customized cell:
#import <Foundation/Foundation.h>
// subclass NSTextFieldCell
#interface InstructionsTextFieldCell : NSTextFieldCell {
}
#end
#import "InstructionsTextFieldCell.h"
#implementation InstructionsTextFieldCell
- (id)init
{
self = [super init];
if (self) {
// Initialization code here. (None needed.)
}
return self;
}
- (void)dealloc
{
[super dealloc];
}
- (NSRect)drawingRectForBounds:(NSRect)rect {
// This gives pretty generous margins, suitable for a large font size.
// If you're using the default font size, it would probably be better to cut the inset values in half.
// You could also propertize a CGFloat from which to derive the inset values, and set it per the font size used at any given time.
NSRect rectInset = NSMakeRect(rect.origin.x + 10.0f, rect.origin.y + 10.0f, rect.size.width - 20.0f, rect.size.height - 20.0f);
return [super drawingRectForBounds:rectInset];
}
// Required methods
- (id)initWithCoder:(NSCoder *)decoder {
return [super initWithCoder:decoder];
}
- (id)initImageCell:(NSImage *)image {
return [super initImageCell:image];
}
- (id)initTextCell:(NSString *)string {
return [super initTextCell:string];
}
#end
(If, like Joshua, you only want an inset at the left, leave the origin.y and height as is, and add the same amount to the width -- not double -- as you do to the origin.x.)
Assign the customized cell like this, in the awakeFromNib method of the window/view controller that owns the textfield:
// Assign the textfield a customized cell, inset so that text doesn't run all the way to the edge.
InstructionsTextFieldCell *newCell = [[InstructionsTextFieldCell alloc] init];
[newCell setBordered:YES]; // so background color shows up
[newCell setBezeled:YES];
[self.tfSyncInstructions setCell:newCell];
[newCell release];
Use a custom NSTextFieldCell that overrides drawingRectForBounds:. Have it inset the rectangle by however much you want, then pass than new rectangle to [super drawingRectForBounds:] to get the normal padding, and return the result of that call.