How to make a text Field on user's click - macos

I want my application to make a text box where ever a user clicks. So how do i synthesize a text box on demand. Kind of like in OneNote.

So how do i synthesize a text box on demand.
You create a text view or text field, and then you add it to your view wherever you want it. Assuming that you have the click event in event and you know the width and height of the text view you want to create, do this:
NSPoint *p = [myContainerView convertPoint:[event locationInWindow] fromView:nil];
NSRect frame = NSMakeRect(p.x, p.y, width, height);
NSTextView *tv = [[NSTextView alloc] initWithFrame:frame];
[myContainerView addSubview:tv];

For detecting mouse event
NSUInteger pmb = [NSEvent pressedMouseButtons];
/*
A return value of 1 << 0 corresponds to the left mouse button, 1 << 1 corresponds to the right mouse button, 1<< n, n >=2 correspond to other mouse buttons.
*/
NSPoint mouseLocation = [NSEvent mouseLocation];
/*
Reports the current mouse position in screen coordinates.
*/

Related

How to do batch display using NSTextView

I'd like to be able to show a view that resembles something like a console log, with multiple lines of text that are scrollable and selectable.
The fundamental procedure I have in mind is maintaining an array of strings (call it lines) and appending these to the textStorage of the NSTextView using a new line character as delimiter.
However there are a few factors to consider, such as:
Updating the textStorage on scroll so that it appears seamless to the user
Updating the textStorage on resizing the view height
Maintaining scroll position after the textStorage gets updated
Handling an out of memory possibility
Can someone please provide some guidance or a sample to get me started?
Add a string from your array to the NSTextStorage and animate the NSClipView bounds origin.
- (void)appendText:(NSString*)string {
// Add a newline, if you need to
string = [NSString stringWithFormat:#"%#\n", string];
// Find range
[self.textView.textStorage replaceCharactersInRange:NSMakeRange(self.textView.textStorage.string.length, 0) withString:string];
// Get clip view
NSClipView *clipView = self.textView.enclosingScrollView.contentView;
// Calculate the y position by subtracting
// clip view height from total document height
CGFloat scrollTo = self.textView.frame.size.height - clipView.frame.size.height;
// Animate bounds
[[clipView animator] setBoundsOrigin:NSMakePoint(0, scrollTo)];
}
If you have elasticity set in your NSTextView you need to monitor for its frame changes to get exact results. Add frameDidChange listener to your text view and animate in the handler:
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
// Text view setup
[_textView setPostsFrameChangedNotifications:YES];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(scrollToBottom) name:NSViewFrameDidChangeNotification object:_textView];
}
- (void)appendText:(NSString*)string {
// Add a newline, if you need to
string = [NSString stringWithFormat:#"%#\n", string];
// Find range
[self.textView.textStorage replaceCharactersInRange:NSMakeRange(self.textView.textStorage.string.length, 0) withString:string];
}
- (void)scrollToBottom {
// Get the clip view and calculate y position
NSClipView *clipView = self.textView.enclosingScrollView.contentView;
// Y position for bottom is document's height - viewport height
CGFloat scrollTo = self.textView.frame.size.height - clipView.frame.size.height;
[[clipView animator] setBoundsOrigin:NSMakePoint(0, scrollTo)];
}
In real-life application you would probably need to set some sort of threshold to see if the user has scrolled away from the end more than the height of a line.

Resizing views dynamically osx

I have two views and a button at the top, i want one be hidden/shown when the button is pressed and for the other views to resize to the edge of the window.
The button on the top left links to an IBAction that hides the lower view with this mainscroll.hidden = true. I can not figure out how to resize/move the other views so the textbox/button are at the bottom of the window, ie no visible gray space at the bottom. I would like to do this programmatically.
http://imgur.com/a/FGH7i
Here is how you can adjust the topView programmatically:
float aHeight = [mainscroll frame].size.height;
NSRect aRect = [topView frame];
aRect.size.height += aHeight;
aRect.origin.y -= aHeight;
[topView setFrame:aRect];

How to accept a mouse click for one portion and let click-though the rest of an NSWindow

I have the code below for a subclassed NSWindow, there is an animated view which can be scaled and I want to accept click when it is clicked at the right spot and reject (click through) if it is outside.
The code below works nice except the window does not let clicks through.
- (void)mouseDragged:(NSEvent *)theEvent {
if (allowDrag) {
NSRect screenVisibleFrame = [[NSScreen mainScreen] visibleFrame];
NSRect windowFrame = [self frame];
NSPoint newOrigin = windowFrame.origin;
// Get the mouse location in window coordinates.
NSPoint currentLocation = [theEvent locationInWindow];
// Update the origin with the difference between the new mouse location and the old mouse location.
newOrigin.x += (currentLocation.x - initialMouseLocation.x);
newOrigin.y += (currentLocation.y - initialMouseLocation.y);
if ((newOrigin.y + windowFrame.size.height) > (screenVisibleFrame.origin.y + screenVisibleFrame.size.height)) {
newOrigin.y = screenVisibleFrame.origin.y + (screenVisibleFrame.size.height - windowFrame.size.height);
}
// Move the window to the new location
[self setFrameOrigin:newOrigin];
}
}
- (void)mouseDown:(NSEvent *)theEvent
{
screenResolution = [[NSScreen mainScreen] frame];
initialMouseLocation = [theEvent locationInWindow];
float scale = [[NSUserDefaults standardUserDefaults] floatForKey:#"widgetScale"]/100;
float pX = initialMouseLocation.x;
float pY = initialMouseLocation.y;
float fX = self.frame.size.width;
float fY = self.frame.size.height;
if (pX>(fX-fX*scale)/2 && pX<(fX+fX*scale)/2 && pY>(fY+fY*scale)/2) {
allowDrag = YES;
} else {
allowDrag = NO;
}
}
In Cocoa, you have two basic choices: 1) you can make a whole window pass clicks through with [window setIgnoresMouseEvents:YES], or 2) you can make parts of your window transparent and clicks will pass through by default.
The limitation is that the window server makes the decision about which app to deliver the event to once. After it has delivered the event to your app, there is no way to make it take the event back and deliver it to another app.
One possible solution might be to use Quartz Event Taps. The idea is that you make your window ignore mouse events, but set up an event tap that will see all events for the login session. If you want to make an event that's going through your window actually stop at your window, you process it manually and then discard it. You don't let the event continue on to the app it would otherwise reach. I expect that this would be very tricky to do right. For example, you don't want to intercept events for another app's window that is in front of yours.
If at all possible, I recommend that you use the Cocoa-supported techniques. I would think you would only want clicks to go through your window where it's transparent anyway, since otherwise how would the user know what they are clicking on?
Please invoke an transparent overlay CHILD WINDOW for accepting control and make the main window -setIgnoresMouseEvents:YES as Ken directed.
I used this tricky on my app named "Overlay".

Is there a "right" way to have NSTextFieldCell draw vertically centered text?

I have an NSTableView with several text columns. By default, the dataCell for these columns is an instance of Apple's NSTextFieldCell class, which does all kinds of wonderful things, but it draws text aligned with the top of the cell, and I want the text to be vertically centered in the cell.
There is an internal flag in NSTextFieldCell that can be used to vertically center the text, and it works beautifully. However, since it is an internal flag, its use is not sanctioned by Apple and it could simply disappear without warning in a future release. I am currently using this internal flag because it is simple and effective. Apple has obviously spent some time implementing the feature, so I dislike the idea of re-implementing it.
So; my question is this: What is the right way to implement something that behaves exactly like Apple's NStextFieldCell, but draws vertically centered text instead of top-aligned?
For the record, here is my current "solution":
#interface NSTextFieldCell (MyCategories)
- (void)setVerticalCentering:(BOOL)centerVertical;
#end
#implementation NSTextFieldCell (MyCategories)
- (void)setVerticalCentering:(BOOL)centerVertical
{
#try { _cFlags.vCentered = centerVertical ? 1 : 0; }
#catch(...) { NSLog(#"*** unable to set vertical centering"); }
}
#end
Used as follows:
[[myTableColumn dataCell] setVerticalCentering:YES];
The other answers didn't work for multiple lines. Therefore I initially continued using the undocumented cFlags.vCentered property, but that caused my app to be rejected from the app store. I ended up using a modified version of Matt Bell's solution that works for multiple lines, word wrapping, and a truncated last line:
-(void)drawInteriorWithFrame:(NSRect)cellFrame inView:(NSView *)controlView {
NSAttributedString *attrString = self.attributedStringValue;
/* if your values can be attributed strings, make them white when selected */
if (self.isHighlighted && self.backgroundStyle==NSBackgroundStyleDark) {
NSMutableAttributedString *whiteString = attrString.mutableCopy;
[whiteString addAttribute: NSForegroundColorAttributeName
value: [NSColor whiteColor]
range: NSMakeRange(0, whiteString.length) ];
attrString = whiteString;
}
[attrString drawWithRect: [self titleRectForBounds:cellFrame]
options: NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin];
}
- (NSRect)titleRectForBounds:(NSRect)theRect {
/* get the standard text content rectangle */
NSRect titleFrame = [super titleRectForBounds:theRect];
/* find out how big the rendered text will be */
NSAttributedString *attrString = self.attributedStringValue;
NSRect textRect = [attrString boundingRectWithSize: titleFrame.size
options: NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin ];
/* If the height of the rendered text is less then the available height,
* we modify the titleRect to center the text vertically */
if (textRect.size.height < titleFrame.size.height) {
titleFrame.origin.y = theRect.origin.y + (theRect.size.height - textRect.size.height) / 2.0;
titleFrame.size.height = textRect.size.height;
}
return titleFrame;
}
(This code assumes ARC; add an autorelease after attrString.mutableCopy if you use manual memory management)
Overriding NSCell's -titleRectForBounds: should do it -- that's the method responsible for telling the cell where to draw its text:
- (NSRect)titleRectForBounds:(NSRect)theRect {
NSRect titleFrame = [super titleRectForBounds:theRect];
NSSize titleSize = [[self attributedStringValue] size];
titleFrame.origin.y = theRect.origin.y + (theRect.size.height - titleSize.height) / 2.0;
return titleFrame;
}
- (void)drawInteriorWithFrame:(NSRect)cellFrame inView:(NSView *)controlView {
NSRect titleRect = [self titleRectForBounds:cellFrame];
[[self attributedStringValue] drawInRect:titleRect];
}
For anyone attempting this using Matt Ball's drawInteriorWithFrame:inView: method, this will no longer draw a background if you have set your cell to draw one. To solve this add something along the lines of
[[NSColor lightGrayColor] set];
NSRectFill(cellFrame);
to the beginning of your drawInteriorWithFrame:inView: method.
FYI, this works well, although I haven't managed to get it to stay centered when you edit the cell... I sometimes have cells with large amounts of text and this code can result in them being misaligned if the text height is greater then the cell it's trying to vertically center it in. Here's my modified method:
- (NSRect)titleRectForBounds:(NSRect)theRect
{
NSRect titleFrame = [super titleRectForBounds:theRect];
NSSize titleSize = [[self attributedStringValue] size];
// test to see if the text height is bigger then the cell, if it is,
// don't try to center it or it will be pushed up out of the cell!
if ( titleSize.height < theRect.size.height ) {
titleFrame.origin.y = theRect.origin.y + (theRect.size.height - titleSize.height) / 2.0;
}
return titleFrame;
}
No. The right way is to put the Field in another view and use auto layout or that parent view's layout to position it.
Though this is pretty old question...
I believe default style of NSTableView implementation is intended strictly for single line text display with all same size & font.
In that case, I recommend,
Set font.
Adjust rowHeight.
Maybe you will get quietly dense rows. And then, give them padding by setting intercellSpacing.
For example,
core_table_view.rowHeight = [NSFont systemFontSizeForControlSize:(NSSmallControlSize)] + 4;
core_table_view.intercellSpacing = CGSizeMake(10, 80);
Here what you'll get with two property adjustment.
This won't work for multi-line text, but very good enough for quick vertical center if you don't need multi-line support.
I had the same problem and here is the solution I did :
1) In Interface Builder, select your NSTableCellView. Make sure it as big as the row height in the Size Inspector. For example, if your row height is 32, make your Cell height 32
2) Make sure your cell is well placed in your row (I mean visible)
3) Select your TextField inside your Cell and go to your size inspector
4) You should see "Arrange" item and select "Center Vertically in Container"
--> The TextField will center itself in the cell

Reposition an NSBox in the top pane of a horizontal NSSplitView

I the issue I'm having has to do with the coordinate system in Cocoa but I really don't know. This is all happening in the top pane of a horizontal NSSplitView.
Very simply, I'm trying to position one NSBox right below a second one (I load custom views into the boxes - that all works fine). The top box's top-left corner is at the top-left corner of the pane and never changes. If the height of the top NSBox shrinks I want the top of the second NSBox to slide right up below it. Conversely, if the top NSBox's height increases I want the bottom NSBox to slide down.
This code gets called twice. Box is correct (first time top box, second time bottom box) and v is correct (this is the view I'm loading into the box - this works fine and it is what is causing the height to change in the top box).
NSSize destBoxSize = [[box contentView] frame].size; //the size of the box in the view to load the view into
NSSize newViewSize = [v frame].size; // the size of the view to be loaded
float deltaWidth = [horizSplitView frame].size.width - destBoxSize.width;
float deltaHeight = newViewSize.height - destBoxSize.height;
NSRect boxFrame = [box frame];
boxFrame.size.height += deltaHeight;
boxFrame.size.width += deltaWidth;
boxFrame.origin.y -= deltaHeight;
NSLog(#"vc=%# boxFrame x%f y%f h%f w%f", nibName, boxFrame.origin.x, boxFrame.origin.y, boxFrame.size.height, boxFrame.size.width);
// Clear the box for resizing
[box setContentView:nil];
[box setContentView:v];
[box setFrame:boxFrame];
What you want to do is not so hard, but it will need some subclassing. First of all, you need to subclass NSSplitView and either and override either -(void)init or -(void)awakeFromNib to add this line:
[self setAutoresizesSubviews:YES]; //
Then you need to subclass the two boxes and set their auto resizing masks, either in -(void)init or in - (void)viewWillMoveToSuperview:(NSView *)newSuperView.
For the first box you'll probably want:
[newInstance setAutoresizingMask:NSViewNotSizable];
For the second bbox you'll probably want:
[newInstance setAutoresizingMask:NSViewMinXMargin | NSViewMinYMargin];
See also NSView. It takes a bit of experimenting to get the right combination, but then it works quite nicely.

Resources