Rectangle 27 1

The NSString of Obj-C is an object, correct the format call with:

NSString *nameText = [NSString stringWithFormat:@"Hello %@",[nameTextField stringValue]];

Note the %@ instead of %s .

cocoa - Concatenating a string with the value of a NSTextField results...

objective-c cocoa string-concatenation nstextfield
Rectangle 27 1

stringValue
NSString
NSString *nameText = [NSString stringWithFormat:@"Hello %@", [nameTextField stringValue]];

cocoa - Concatenating a string with the value of a NSTextField results...

objective-c cocoa string-concatenation nstextfield
Rectangle 27 0

Using NSTextView, its a multiline NSTextField sorta, it is a subclass of NSText correct my if I am wrong. The NSTextView has an NSTextStorage, which is a subclass of NSAttributedString. You need to give it an NSAttributedString object instead of a NSString to fill its contents as it can display colors etc.

objective c - Cocoa : How to make multiline NSTextField? - Stack Overf...

objective-c cocoa osx
Rectangle 27 0

Could someone explain to me what are the main differences between NSTextField and NSTextView? I know that NSTextView has more features and is usually used for longer texts, and NSTextField is usually used for one-line plain text fields, but if I understand correctly, NSTextField can be also used with attributed strings and with multiple lines...

Technically true, but you normally use text fields for values that are plain text and usually only one line. (Handle multiple lines, as a text field can accept them. If nothing else, strip the line breaks in a way that makes sense for what you're doing with the text.)

  • it should display text in about 1-4 lines
  • it should be able to show links in the text (as I understand, this should be simple in both controls - http://developer.apple.com/mac/library/qa/qa2006/qa1487.html)

NSTextView. Supporting links in an NSTextField is tricky.

  • it should let the user select and copy the text
  • it should NOT let the user scroll the text,

NSTextField or NSTextView without NSScrollView. You can do the latter in IB by dragging a text view from the Library and then choosing Unembed Objects from the Layout menu.

or show the context menu that usually appears in editable text fields,

Yes, it should. You should always offer menu items like Copy and read-only services. Either control should do this for you; don't fight this.

it shouldn't even show a text cursor in this field

If you leave selection enabled (which you generally should), they'll show a cursor if the user clicks in the field. This is a feature, as it indicates where the selection anchor is for shift--arrow selection.

With such requirements, is it better for me to use a NSTextField or NSTextView?

Thanks for the info. Looks like everything is working fine now, I also managed to disable the text cursor using shouldDrawInsertionPoint. One thing I wasn't able to do was to convince it to always show an arrow cursor instead of the X-shaped one, but I can live with that...

@Psionides: X-shaped? You mean the I-beam? You could try sending discardCursorRects to the text view.

cocoa - NSTextField or NSTextView? - Stack Overflow

cocoa osx text nstextfield nstextview
Rectangle 27 0

I am glad you discovered the comments in my blog post. I think they are the tip of the iceberg to discovering how to achieve what you're looking for.

You need to keep in mind that the reason dragging to an NSTextField works when it has focus, is that the NSTextField has itself been temporarily obscured by a richer, more powerful view (an NSTextView), which is called the "Field Editor."

Check out this section of Apple's documentation on the field editor:

To achieve what you're striving for, I think you might need to intercept the standard provision of the field editor for your NSTextFields, by implementing the window delegate method:

This gives you the opportunity to either tweak the configuration on the NSTextView, or provide a completely new field editor object.

In the worst case scenario, you could provide your own NSTextView subclass as the field editor, which was designed to reject all drags.

cocoa - How to disable drag-n-drop for NSTextField? - Stack Overflow

cocoa drag-and-drop nstextfield nsdragginginfo
Rectangle 27 0

If you're just showing content, as opposed to typing in the text field, then you should use a label, which can be set in IB to "Size To Fit Content". This will cause the label to be just big enough for the content.

cocoa - How to resize NSTextField when content increase in NSTextField...

cocoa nstextfield nstextview
Rectangle 27 0

#import <Cocoa/Cocoa.h>

@interface EditTextField : NSTextField <NSTextDelegate,NSTextViewDelegate,NSTextFieldDelegate>

@property BOOL isEditing;
@property BOOL commitChangesOnEscapeKey;
@property BOOL editAfterDelay;
@property CGFloat delay;

@end

----


#import "EditTextField.h"

@interface EditTextField ()
@property NSObject <NSTextFieldDelegate,NSTextViewDelegate> * userDelegate;
@property NSString * originalStringValue;
@property NSTimer * editTimer;
@property NSTrackingArea * editTrackingArea;
@end

@implementation EditTextField

- (id) initWithCoder:(NSCoder *)coder {
    self = [super initWithCoder:coder];
    [self defaultInit];
    return self;
}

- (id) initWithFrame:(NSRect)frameRect {
    self = [super initWithFrame:frameRect];
    [self defaultInit];
    return self;
}

- (id) init {
    self = [super init];
    [self defaultInit];
    return self;
}

- (void) defaultInit {
    self.delay = .8;
}

- (void) mouseDown:(NSEvent *) theEvent {
    if(theEvent.clickCount == 2) {
        [self startEditing];
    } else {
        [super mouseDown:theEvent];
        if(self.editAfterDelay) {
            [self startTracking];
            self.editTimer = [NSTimer scheduledTimerWithTimeInterval:.8 target:self selector:@selector(startEditing) userInfo:nil repeats:FALSE];
        }
    }
}

- (void) startTracking {
    if(!self.editTrackingArea) {
        self.editTrackingArea = [[NSTrackingArea alloc] initWithRect:self.bounds options:NSTrackingMouseEnteredAndExited|NSTrackingMouseMoved|NSTrackingActiveInActiveApp|NSTrackingAssumeInside|NSTrackingInVisibleRect owner:self userInfo:nil];
    }
    [self addTrackingArea:self.editTrackingArea];
}

- (void) mouseExited:(NSEvent *)theEvent {
    [self.editTimer invalidate];
    self.editTimer = nil;
}

- (void) mouseMoved:(NSEvent *) theEvent {
    [self.editTimer invalidate];
    self.editTimer = nil;
}

- (void) startEditing {
    id firstResponder = self.window.firstResponder;
    if([firstResponder isKindOfClass:[NSTextView class]]) {
        NSTextView * tv = (NSTextView *)firstResponder;
        if(tv.delegate && [tv.delegate isKindOfClass:[EditTextField class]]) {
            EditTextField * fr = (EditTextField *)tv.delegate;
            [fr stopEditingCommitChanges:FALSE clearFirstResponder:FALSE];
        }
    }
    if(self.delegate != self) {
        self.userDelegate = (NSObject <NSTextFieldDelegate,NSTextViewDelegate> *)self.delegate;
    }
    self.isEditing = TRUE;
    self.delegate = self;
    self.editable = TRUE;
    self.originalStringValue = self.stringValue;
    [self.window makeFirstResponder:self];
}

- (void) stopEditingCommitChanges:(BOOL) commitChanges clearFirstResponder:(BOOL) clearFirstResponder {
    self.editable = FALSE;
    self.isEditing = FALSE;
    self.delegate = nil;
    [self removeTrackingArea:self.editTrackingArea];
    if(!commitChanges) {
        self.stringValue = self.originalStringValue;
    }
    if(clearFirstResponder) {
        [self.window makeFirstResponder:nil];
    }
}

- (void) cancelOperation:(id) sender {
    if(self.commitChangesOnEscapeKey) {
        [self stopEditingCommitChanges:TRUE clearFirstResponder:TRUE];
    } else {
        [self stopEditingCommitChanges:FALSE clearFirstResponder:TRUE];
    }
}

- (BOOL) textView:(NSTextView *) textView doCommandBySelector:(SEL) commandSelector {
    BOOL handlesCommand = FALSE;
    NSString * selector = NSStringFromSelector(commandSelector);

    if(self.userDelegate) {

        if([self.userDelegate respondsToSelector:@selector(control:textView:doCommandBySelector:)]) {
            handlesCommand = [self.userDelegate control:self textView:textView doCommandBySelector:commandSelector];
        } else if([self.userDelegate respondsToSelector:@selector(textView:doCommandBySelector:)]) {
            handlesCommand = [self.userDelegate textView:textView doCommandBySelector:commandSelector];
        }

        if(!handlesCommand) {

            if([selector isEqualToString:@"insertNewline:"]) {
                [self stopEditingCommitChanges:TRUE clearFirstResponder:TRUE];
                handlesCommand = TRUE;
            }

            if([selector isEqualToString:@"insertTab:"]) {
                [self stopEditingCommitChanges:TRUE clearFirstResponder:FALSE];
                handlesCommand = FALSE;
            }
        }

    } else {

        if([selector isEqualToString:@"insertNewline:"]) {
            [self stopEditingCommitChanges:TRUE clearFirstResponder:TRUE];
            handlesCommand = TRUE;
        }

        if([selector isEqualToString:@"insertTab:"]) {
            [self stopEditingCommitChanges:TRUE clearFirstResponder:FALSE];
            handlesCommand = FALSE;
        }
    }

    return handlesCommand;
}

@end

osx - Cocoa: Making NSTextField editable after a click and short delay...

osx cocoa fieldeditor
Rectangle 27 0

May I ask why you wish to disable this feature? It's a pretty standard part of the OS. Bear in mind that the user might well paste in some string from elsewhere that contains a line break and they'll then edit to their needs. Would it perhaps be better to leave this feature intact, but use an NSFormatter to strip out everything after the line break when it is time to copy the value out of the view to the model?

cocoa - Disable Option-Enter line breaks in NSTextField? - Stack Overf...

cocoa nstextfield nstextview fieldeditor
Rectangle 27 0

Those links should show you the way :

They talk about iPhone classes, but I'm sure you will be able to adapt them for NSTextField.

NSTextField subclass for sliding text - Objective-C/Cocoa - Stack Over...

objective-c cocoa subclass nstextfield ticker
Rectangle 27 0

Unless runthis is located in a separate nib, it's outlet won't be connected automatically, you'll have to pass it as a reference. In testing you'll have to wire up the text field, then pass it to runthis like:

[testSomething setStatusField:updateStatus];

Or you could create a reference to your testing object from your runthis object (call it a delegate) and have testing update the UI directly. That's the approach I would use.

I don't understand the last part of your comment. How would I create a ref. to the testing object from runthis and update the UI directly ?

@ZionKing: Add a property to your runthis object that takes a testing objector something that conforms to a protocol that runthis declares. Have testing conform to the protocol (if you go that way) and set itself as the runthis's delegate. When runthis needs to get the field's value changed, have it send a message to its delegate, and have the testing object respond to that message by getting the runthis object's statusField and setting its value.

Not sure I get this yet. Are there any examples ? Thanks and appreciate all the help and patience :).

cocoa - NSTextfield not getting updated when called from another class...

cocoa uilabel nstextfield
Rectangle 27 0

stringValue
NSString
NSString *nameText = [NSString stringWithFormat:@"Hello %@", [nameTextField stringValue]];

cocoa - Concatenating a string with the value of a NSTextField results...

objective-c cocoa string-concatenation nstextfield
Rectangle 27 0

@Abhay, NSTextField is in Cocoa and UITextField in UIKit. It is not a spelling mistake

If you're going to use becomeFirstResponder and resignFirstResponder it'll also be worth your while to become familiar with the operation of the window's fieldEditor. This object (an NSTextView subclass) is where you're editing actually happens and it's worth knowing about because when you think your NSTextField has focus, it doesn't - the field editor does. Appreciating this help you understand why you're NSTextField is not the first responder even when you're happily typing text into it.

Excellent!. I had to call a custom delegate from inside overriding the become first responder then listen for that "event".

NSTextField GotFocus Event Cocoa Swift - Stack Overflow

cocoa swift events focus nstextfield
Rectangle 27 0

In the text field delegate, you can follow all standard commands are sent to the control. Then, once you meet a command noon:, test for current key combination. If it is Command-Enter, do your thing. Something like this should work:

@interface VCEAppDelegate : NSObject <NSApplicationDelegate, NSTextFieldDelegate>
@property (nonatomic, weak) IBOutlet NSTextField *textField;
@end

// .m
@implementation VCEAppDelegate

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
    self.textField.delegate = self;
}

- (BOOL)isCommandEnterEvent:(NSEvent *)e {
    NSUInteger flags = (e.modifierFlags & NSDeviceIndependentModifierFlagsMask);
    BOOL isCommand = (flags & NSCommandKeyMask) == NSCommandKeyMask;
    BOOL isEnter = (e.keyCode == 0x24); // VK_RETURN
    return (isCommand && isEnter);
}

- (BOOL)control:(NSControl *)control textView:(NSTextView *)textView
                          doCommandBySelector:(SEL)commandSelector {
    if ((commandSelector == @selector(noop:)) &&
        [self isCommandEnterEvent:[NSApp currentEvent]]) {
        [self handleCommandEnter];
        return YES;
    }
    return NO;
}

- (void)handleCommandEnter {
    NSLog(@"Do something on Command-Enter");
}

@end

Glad you worked it out! Though in terms of class design my solution is more decoupled. If you are working on a comparably big app, please ensure that you really want to subclass NSApplication and micro-manage that particular event. Good luck :)

- (BOOL)textView:(NSTextView *)textView doCommandBySelector:(SEL)commandSelector
- (BOOL)control:(NSControl *)control textView:(NSTextView *)textView doCommandBySelector:(SEL)commandSelector

cocoa - Add HotKey to NSTextField - Stack Overflow

cocoa hotkeys
Rectangle 27 0

- (void) sendEvent:(NSEvent*) event {
    if ([event type] == NSKeyDown) {
        if (([event modifierFlags] & NSDeviceIndependentModifierFlagsMask) == NSCommandKeyMask) {
            if ([event keyCode] == 36) {
                if ([self.delegate respondsToSelector:@selector(sendMessage:)]) {
                    [self.delegate performSelector:@selector(sendMessage:) withObject:nil];
                }
            }
        }
    }

    [super sendEvent:event];
}

in info.plist I wrote that this sub-NSApplication class is a Principal class. It works!

cocoa - Add HotKey to NSTextField - Stack Overflow

cocoa hotkeys
Rectangle 27 0

Ok, I've found a way to do it: use a window delegate to make the window return a custom field editor. This field editor keeps track of the last TextField that's been activated and calls its textDidEndEditting method when losing firstResponder itself. Here's an example of how to do it:

#import <Cocoa/Cocoa.h>
#import <AppKit/AppKit.h>


@interface MyTextField : NSTextField
- (BOOL)resignFirstResponder;
- (void)textDidEndEditing:(NSNotification *)notification;
@end

@interface MyFieldEditor : NSTextView
{
    MyTextField * lastBox;
}
-(void) setLastEditBox:(MyTextField*) box;
@end

@interface MyWindowDelegate : NSWindowController 
{
    MyFieldEditor *fieldEditor;
}
@end



@implementation MyFieldEditor

-(void) setLastEditBox:(MyTextField*) box{ lastBox = box; }

-(id)init
{
    if (self = [super init]) 
        [self setFieldEditor:YES];

    return self;
}

- (BOOL)resignFirstResponder
{
    // Activate the last active editbox editting-end event
    if(lastBox != nil)
    {
        [lastBox textShouldEndEditing:self];
        lastBox = nil;
    }

    return [super resignFirstResponder];
}

@end


@implementation MyWindowDelegate

-(id)windowWillReturnFieldEditor:(NSWindow *)sender toObject:(id)client
{
    if(fieldEditor == nil)  // Return our special field editor
        fieldEditor = [[[MyFieldEditor alloc] autorelease] init];
    return fieldEditor;
}
@end


@implementation MyTextField

- (BOOL)resignFirstResponder
{
    // We're losing first responder, inform the field editor that this was the last edit box activated
    MyFieldEditor* myTf = (MyFieldEditor*) [[self window] fieldEditor:YES forObject:self];
    [myTf setLastEditBox:self];
    return [super resignFirstResponder];
}

- (void)textDidEndEditing:(NSNotification *)notification;
{
    [super textDidEndEditing:notification];
    [self setStringValue:@"RECEIVED ENDEDITING"];
}

@end




int main(int argc, char *argv[])
{   
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    NSApplication *app = [NSApplication sharedApplication];

    NSRect frame = NSMakeRect(100, 100, 200, 150);

    // Create the window
    NSWindow* window  = [[[NSWindow alloc] autorelease ] initWithContentRect:frame styleMask:NSClosableWindowMask|NSResizableWindowMask
                                                      backing:NSBackingStoreBuffered defer:NO];

    [window setDelegate:[[MyWindowDelegate alloc] autorelease]];


    MyTextField * tf = [ [[ MyTextField alloc ] autorelease] initWithFrame: NSMakeRect( 30.0, 100.0, 150.0, 22.0 ) ];
    [ [ window contentView ] addSubview: tf ];

    MyTextField * tf2 = [ [[ MyTextField alloc ] autorelease] initWithFrame: NSMakeRect( 30.0, 40.0, 150.0, 22.0 ) ];
    [ [ window contentView ] addSubview: tf2 ];

    [window makeKeyAndOrderFront: window];  

    [app run];
    [pool release];

    return 0;
}

cocoa - NSTextField not noticing lost focus when pressing Tab? - Stack...

cocoa focus nstextfield
Rectangle 27 0

Here's an example of how to indicate the appropriate time a custom NSTextFieldCell (NSCell) should draw its own bezel & focus ring (in the method [NSTextFieldCell drawWithFrame: inView]), by 'borrowing' the cell's highlight field, setting it when the text field gains focus, and clearing it when the text field loses focus (editing completes).

  • The cell can't easily determine which higher level component (e.g. text field or button) it belongs to to track via its parent
  • NSTextField can instantaneously resign first responder after gaining it, which could make it seem like it lost user focus when it didn't.

Since we're re-purposing the cell's "highlighted" state field, in order to communicate the focus state to the cell, be sure to return nil from the custom NSTextFieldCell's [highlightColorWithFrame: inView:] method.

#import "CustomTextField.h"

@implementation CustomTextField

-(BOOL)becomeFirstResponder {
    ((NSTextFieldCell *)self.cell).highlighted = true;
    return [super becomeFirstResponder];
}

 -(void)textDidEndEditing:(NSNotification *)notification {
    ((NSTextFieldCell *)self.cell).highlighted = false;
    [super textDidEndEditing:notification];
} 
@end

cocoa - NSTextField not noticing lost focus when pressing Tab? - Stack...

cocoa focus nstextfield
Rectangle 27 0

(it is the OP that answers his own question :) ).

cocoa - Change the line height (leading) in NSTextField - Stack Overfl...

cocoa interface-builder nstextfield
Rectangle 27 0

You can subclass NSTableRowView and override -[NSTableRowView interiorBackgroundStyle] to return NSBackgroundStyleLight. This will tell the cells that they are on a light background and to draw dark text, which will be black.

NSTableCellView
-[NSTableCellView setBackgroundStyle:]

cocoa - How to change NSTextField text color on row selection? - Stack...

cocoa nstextfield
Rectangle 27 0

- (BOOL)saveChanges:(NSError **)outError {
  BOOL result = YES;
  @try {
    NSError *error = nil; 
    if ([self hasChanges])  {

    // Get field editor
    NSResponder *responder = [[NSApp keyWindow] firstResponder];
    NSText *editor = [[NSApp keyWindow] fieldEditor: NO forObject: nil];
    id editingObject = [editor delegate];
    BOOL isEditing = (responder == editor);
    NSRange range;
    NSInteger editedRow, editedColumn;

   // End editing to commit the last changes
   if (isEditing) {

     // Special case for tables
     if ([editingObject isKindOfClass: [NSTableView class]]) {
       editedRow = [editingObject editedRow];
       editedColumn = [editingObject editedColumn];
     }

     range = [editor selectedRange];
     [[NSApp keyWindow] endEditingFor: nil];
   }

   // The actual save operation
   if (![self save: &error]) {
     if (outError != nil)
        *outError = error;
      result = NO;
    } else {
      result = YES;
    }

    // Now restore the field editor, if any.
    if (isEditing) {
      [[NSApp keyWindow] makeFirstResponder: editingObject];
      if ([editingObject isKindOfClass: [NSTableView class]])
        [editingObject editColumn: editedColumn row: editedRow withEvent: nil select: NO];
        [editor setSelectedRange: range];
      }
    }
  } @catch (id exception) {
    result = NO;
  }
  return result;
}

Except of course the edit point may not be at the end (or there could even be a selection). Just capture the [editor selectedRange] NSRange before ending editing, then [editor setSelectedRange:] using the saved NSRange.

You're right. I had already improved the code and added support for NSTableView. I have now edited my answer to share it with you. Please note that this is a stripped version of my actual code, which also includes thread safety and error handling.

cocoa - NSManagedObjectContext save causes NSTextField to lose focus -...

cocoa osx core-data focus nstextfield
Rectangle 27 0

I could not for the life of me find a way to reference the label in the subview I added to the windows titlebar via IB, so the best workaround I can find is this :

class WindowControler: NSWindowController {

    var titlebarLabel:NSTextField?

    override func windowDidLoad() {
        super.windowDidLoad()
        // add the titlebar subview
        window?.addTitlebarAccessoryViewController(TitlebarSubviewControler(nibName: "TitlebarSubview", bundle: NSBundle.mainBundle())!)
        // get reference to the titlibarLabel I just added in the line above
        var subviewsOfTheLastTitleBarView: AnyObject? = window?.standardWindowButton(NSWindowButton.ZoomButton)?.superview?.subviews.last?.subviews[0]
        var titlebarNSTextField: AnyObject? = subviewsOfTheLastTitleBarView?.subviews[0]
        titlebarLabel = (titlebarNSTextField! as NSTextField)
    }

    @IBAction func tempbuttonclicked(sender: AnyObject) {
        titlebarLabel?.stringValue = "Text seen in titlebar subview"
    }

}

So I am hunting through the titlebar here, to find the NSTextField right after I add it to the titlebar in the first line of windowDidLoad, and taking a lot for granted.

I am pretty worried this could break very easily, just not sure about doing it like this. Any better solutions greatly appreciated.

cocoa - IBOutlet for NSTextField in NSTitlebarAccessoryView - Stack Ov...

cocoa swift desktop-application iboutlet