NSTextField handling Enter key presses strangely - cocoa

I'm sure I'm just using it incorrectly, but what I'm doing is I have a NSTextField with a attributed string with a few characters of text in a different font at the end of it. When the user clicks the text field, the text at the end should disappear, and when the user finishes editing their text and removes focus from the text field, the text gets added back to the end of the string they entered.
It's working fine when then user tabs out of the box, or clicks somewhere on the window to remove focus from the textfield. The only time it doesn't work is if they hit the "return" key in the text box. The text still gets added to the end of their string in this case, but it's in the same font as the rest of the string.
Here is the relevant portion of my code. I've verified that both methods are being called in the same sequence both when I tab out of a field and when I hit enter in the field.
- (void) selectText:(id)sender
{
[titleText setStringValue: [NSString stringWithFormat:#"%#", userEditableText]];
}
- (void) textDidEndEditing:(NSNotification *)notification
{
userEditableText = [textField stringValue];
NSString* fullText = [NSString stringWithFormat:#"%# (%#)", userEditableText, nonUserEditableText];
NSRange range1;
range1.location = 0;
range1.length = [userEditableText length] - ([nonUserEditableText length] + 2);
NSRange range2;
range2.location = range1.length;
range2.length = ([[nonUserEditableText length] length] + 2);
NSRange range3;
range3.location = 0;
range3.length = [fullText length];
NSFont *font = [NSFont fontWithName:#"Arial" size:14.0];
NSMutableDictionary* stringAttributes = [[NSMutableDictionary alloc] init];
NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:fullText attributes:stringAttributes];
NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
[paragraphStyle setLineBreakMode:NSLineBreakByTruncatingMiddle];
[attrString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:range1];
[attrString addAttribute:NSFontAttributeName value:font range:range2];
[textField setAttributedStringValue:attrString];
}

Not sure exactly what I did, but I changed around a bunch of code in several classes and now everything is working properly. Wish I knew what I did...

Related

i want to paste selected text in a text view on button click named paste.how can i do this?

I am new to cocoa prgramming, and I am copying text using the code:
NSRange range = [textView selectedRange];
NSData* rtfData = [textView RTFFromRange: range];
NSAttributedString* aStr = [[NSAttributedString alloc]initWithRTF:rtfData documentAttributes:NULL];
NSString* str = [aStr string];
str contains the selected text, but how can I paste that text in a NSTextView whenever I click in a textview?
you have to set delegate of NSTextView to self, then you need to implement delegate method on which you want to perform this action.
And then you can use setString method of NSText(Super class of NSTextView) to set the text.
Edit - (Try with this first, if it set the text to textview)
NSRange range = [textView selectedRange];
NSData* rtfData = [textView RTFFromRange: range];
NSAttributedString* aStr = [[NSAttributedString alloc]initWithRTF:rtfData documentAttributes:NULL];
NSString* str = [aStr string];
[[textView setString:str];
for NSTextView you need :
[[textView textStorage] setAttributedString:[[NSAttributedString alloc] initWithString:str]];

NSButton setAlignment does not work

I used
[button setAlignment:NSCenterTextAlignment];
to make the text display at the center of the button.
It worked.
But if I set button title attribute before the code, button 'setAlignment' will not work
- (void)setButtonTitle:(NSButton*)button fontName:(NSString*)fontName fontSize:(CGFloat)fontSize fontColor:(NSColor*)fontColor;
{
NSMutableAttributedString *attributedString =
[[NSMutableAttributedString alloc] initWithString:[button title]
attributes:[NSDictionary dictionaryWithObject:[NSFont fontWithName:fontName size:fontSize]
forKey:NSFontAttributeName]];
[attributedString addAttribute:NSForegroundColorAttributeName
value:fontColor
range:NSMakeRange(0, [[button title] length] )];
[button setAttributedTitle: attributedString];
[button setAlignment:NSCenterTextAlignment];//button title alignment always displayed as 'NSLeftTextAlignment' rather than 'NSCenterTextAlignment'.
}
title alignment always displayed as 'NSLeftTextAlignment' rather than 'NSCenterTextAlignment'.
Welcome any comment
Since you’re using an attributed string for the button title, the attributes in that string are responsible for setting the alignment.
To centre that attributed string, add an NSParagraphStyleAttributeName attribute with a centred alignment value:
NSMutableParagraphStyle *centredStyle = [[[NSParagraphStyle defaultParagraphStyle] mutableCopy] autorelease];
[centredStyle setAlignment:NSCenterTextAlignment];
NSDictionary *attrs = [NSDictionary dictionaryWithObjectsAndKeys:centredStyle,
NSParagraphStyleAttributeName,
[NSFont fontWithName:fontName size:fontSize],
NSFontAttributeName,
fontColor,
NSForegroundColorAttributeName,
nil];
NSMutableAttributedString *attributedString =
[[NSMutableAttributedString alloc] initWithString:[button title]
attributes:attrs];
[button setAttributedTitle: attributedString];
In the code above, I’ve created a single attrs dictionary holding all the attributes for the attributed string. From your code, it looks like the font colour should be applied to the whole string anyway.

Cocoa. Create NSTextView, add an NSString to it and print

I have a window with a button for printing receipts. What I need to do is to create a simple NSTextView, add an NSString to it (at least something like "Hello World") and print it without displaying NSTextView on the window.
Here is what I currently have:
NSTextView *textView = [[NSTextView alloc] init];
NSString *text = #"testing";
[textView setEditable:true];
NSRange range = NSMakeRange( 0, [[textView string] length]);
[textView setSelectedRange:range];
[[[textView textStorage] mutableString] appendString:text];
NSPrintOperation *printOperation;
printOperation = [NSPrintOperation printOperationWithView:textView];
[printOperation runOperation];
when I run it, I see printing dialog, but preview is empty.
When I change printOperationWithView:textView]; from textView to one of the existing views on my window, it prints ok.
The main thing is.. I don't want to display the view after I click Print button. Ideally I would like to print the text, not the view.
Have you tried using -initWithFrame with a nonzero rect?
NSTextView *textview = [[NSTextView alloc] initWithFrame:NSMakeRect(0, 0, 468, 648);
(468 x 648 would make it fit an A4 sheet with 1-inch margins.)
Here is an implementation which works in an NSDocument subclass. Modify it to suit your needs.
- (NSPrintOperation *)printOperationWithSettings:(NSDictionary<NSString *,id> *)printSettings error:(NSError * _Nullable __autoreleasing *)outError
{
NSPrintInfo * printInfo = [self printInfo];
printInfo.topMargin = 15.0;
printInfo.leftMargin = 10.0;
printInfo.rightMargin = 10.0;
printInfo.bottomMargin = 15.0;
printInfo.verticallyCentered = NO;
NSRect bounds = printInfo.imageablePageBounds;
NSTextView * printView = [[NSTextView alloc] initWithFrame:bounds];
printView.autoresizingMask = NSViewWidthSizable | NSViewHeightSizable;
[printView.textStorage appendAttributedString:self.attributedStringRepresentation];
return [NSPrintOperation printOperationWithView:printView printInfo:printInfo];
}
Have you tried just:
[textView print];
This is very good. Just one more enhancement. In order for the print out not to be centered, and to fill up the page correctly, pass printInfo in as a parameter.
NSPrintOperation *printOperation;
NSPrintInfo *pInfo = [[NSPrintInfo alloc] init];
[pInfo setBottomMargin:50];
[pInfo setTopMargin:50];
[pInfo setVerticallyCentered:false];
printOperation = [NSPrintOperation printOperationWithView:textView printInfo:pInfo];
[printOperation runOperation];

Showing image before text in NSButtonCell in NSMatrix

I am displaying buttons in NSMatrix.
My requirement is:
to change color of button title and
place an image at beginning of title, when certain condition is satisfied.
To do so, I used following code:
// setting attributed text
NSAttributedString *selectedCellAttribute;
NSFont *selectedCellFont = [NSFont fontWithName:#"Lucida Grande" size:11];
NSColor *selectedCellColor = [NSColor redColor];
NSMutableParagraphStyle *style = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
[style setAlignment:NSCenterTextAlignment];
// setting image
NSTextAttachment *imageAttachment = [[NSTextAttachment alloc] init];
NSCell *cell = [imageAttachment attachmentCell];
[cell setImage:[NSImage imageNamed:#"caution_small.png"]];
NSDictionary *selectedCellDictionary = [NSDictionary dictionaryWithObjectsAndKeys:imageAttachment,NSAttachmentAttributeName,selectedCellFont,NSFontAttributeName,selectedCellColor,NSForegroundColorAttributeName,style,NSParagraphStyleAttributeName,nil];
// recognizing cell
NSButtonCell *associatedCell = [associatesMatrix cellAtRow:0 column:2];
selectedCellAttribute = [[NSAttributedString alloc] initWithString:[associatedCell title] attributes:selectedCellDictionary];
[associatedCell setAttributedTitle:selectedCellAttribute];
Although above code is showing change in color of title, it is showing no image placed in beginning of title :(
Can anyone suggest me where I may be wrong or some other method to implement my requirements?
EDIT:
At line:
NSCell *cell = [imageAttachment attachmentCell];
it is giving this warning when compiled:
type 'id <NSTextAttachmentCell>' does not conform to 'NSCopying" protocol.
Thanks,
Miraaj
You've set the attachment for the entire string. What you need to do is prefix the string with NSAttachmentCharacter, and set the attachment only for that section of the string.
You may want to put a space between the NSAttachmentCharacter and your actual text. Only the NSAttachmentCharacter should have the attachment attribute.

Trying to create link with NSTextField

I'm using this category (is that right?) http://www.nightproductions.net/references/dsclickableurltextfield_reference.html#setAttributedStringValue
to implement clickable textfields. I've imported the header file in my controller class and set it's attributed string value like this
NSAttributedString* str = [[NSAttributedString alloc] initWithString:#"http://www.yahoo.com"];
[url setAttributedStringValue:(NSAttributedString *)str];
[str release];
The text field is not selectable and not editable.
The text field value is set but it's not clickable and it's not a link.
Thanks in advance.
I have found another easy way to show links in NSTextField. You can use HTML. Here is a short example:
-(NSAttributedString *)stringFromHTML:(NSString *)html withFont:(NSFont *)font
{
if (!font) font = [NSFont systemFontOfSize:0.0]; // Default font
html = [NSString stringWithFormat:#"<span style=\"font-family:'%#'; font-size:%dpx;\">%#</span>", [font fontName], (int)[font pointSize], html];
NSData *data = [html dataUsingEncoding:NSUTF8StringEncoding];
NSAttributedString* string = [[NSAttributedString alloc] initWithHTML:data documentAttributes:nil];
return string;
}
Now you can call the method for text field:
// #property IBOutlet NSTextField *tf;
[tf setAllowsEditingTextAttributes: YES];
[tf setSelectable:YES];
NSString *credits = #"Visit our webpage";
[tf setAttributedStringValue:[self stringFromHTML:credits withFont:[tf font]]];

Resources