ok I have a press basic application with the following code in newAppViewController.m
When I run my app, the label i have called myLabel changes the text but the color of the view ALWAYS becomes blue not red. For some reason its always the else case!
Any Ideas?
-(IBAction)click:(id)sender{
NSString *mystr = [[NSString alloc]initWithFormat:#"%#",[[sender titleLabel] text] ];
myLabel.text = mystr;
if(myLabel.text == #"RED")
self.view.backgroundColor = [UIColor redColor];
else self.view.backgroundColor = [UIColor blueColor];
}
Why don't you try with
if([myLabel.text isEqualToString:#"RED"])
You can't compare two string with "==" operator. Use the -isEqualToString: method for this.
To compare two scalars you have to use the == operator; When you are comparing objects you have to use the -isEqual: method, and when you are comparing strings you have to use the --isEqualToString: method.
Related
I am trying to change text font size with using NSAttributedString. But it's size doesn't change.
NSDictionary *attrDict = #{NSFontAttributeName : [UIFont boldSystemFontOfSize:22], NSForegroundColorAttributeName : [UIColor orangeColor]};
NSAttributedString *newAttString = [[NSAttributedString alloc] initWithString:mytext attributes:attrDict];
[result appendAttributedString:newAttString];
Only text color changes. Size of result string is not 22 and also it is not bold.
Instead of applying the attributes with the alloc, init, try doing it after with something like (with a mutable NSAttributedString):
NSMutableAttributedString *newAtt = [[NSMutableAttributedString alloc] initWithString:mytext]; // Allocate a new NSMutableAttributedString with `mytext`
[newAtt addAttributes:#{NSFontAttributeName : [UIFont boldSystemFontOfSize:20],
NSForegroundColorAttributeName: [UIColor orangeColor]}
range:NSMakeRange(0, [result length])]; // add new attributes for the length of the string `mytext`
[result setAttributedText:newAtt];
This answer would vary depending on what result is, I tested it on a UITextView and it worked fine, there is also an attributedText
property on UILabels.
Hope this helps.
You didn't mention what result means at the end of your code. Are you sure you want to "append" it?
Besides, I use this code for setting fonts
[UIFont fontWithName:#"Arial-BoldMT" size:22.0f]
This can be used to set different fonts and sizes respectively.
Hope this helps:)
Beginner to objective-c, so please excuse basic mistakes.
Goal is to set predictionLabel.textColor to a random color from an array.
// fill array colors
self.colors = #[#"redColor", #"greenColor", #"blueColor", #"greyColor", #"orangeColor", #"purpleColor"];
// get random number based on array count
int randomColor = arc4random_uniform(self.colors.count);
// set predictionLabel.textColor to random color
self.predictionLabel.textColor = [UIColor [self.colors objectAtIndex:randomColor]];
I keep getting the error message "Expected identifier" at [UIColor [self.colors.
Being new, I'm having a hard time troubleshooting this one. Any advice?
You're not using Key Value Coding, though you want to. You're really just guessing about the method names that might be on UIColor. Why not use an array of UIColor objects instead of the names of the class methods. Like this:
self.colors = #[[UIColor redColor], [UIColor greenColor], [UIColor blueColor], [UIColor grayColor], UIColor orangeColor], [UIColor purpleColor]];
// get random number based on array count
int randomColor = arc4random_uniform(self.colors.count);
// set predictionLabel.textColor to random color
self.predictionLabel.textColor = [self.colors objectAtIndex:randomColor];
Also, watch the spelling of "grey" vs "gray". [UIColor greyColor] doesn't exist.
What you're trying to do is like doing:
[UIColor #"redColor"];
which just won't compile and is not valid syntax.
If you insist on using strings, you could do:
self.predictionLabel.textColor = [UIColor valueForKey:[self.colors objectAtIndex:randomColor]];
I've got an NSTask (with an NSPipe set up) running in the background and I want to output the contents, as they're coming in, in an NSTextView (output).
The code I'm using is :
NSMutableAttributedString* str = [[NSMutableAttributedString alloc] initWithString:s];
//[str addAttribute:NSForegroundColorAttributeName value:[NSColor whiteColor] range:NSMakeRange(0, [str length])];
[[output textStorage] appendAttributedString:str];
[output scrollRangeToVisible:NSMakeRange([[output string] length], 0)];
Issues :
When there is a lot of data appending, the view seems like "flashing"... and not working properly.
Given that the NSTextView is on a Sheet, NO CONTENTS seem to be appearing when the mouse pointer is elsewhere other than hovering above the NSTextView
Why is that, although I've set the color/insertion color/etc of the NSTextView, this doesn't seem to apply to newly inserted text?
What's the suggested way of appending (+scrolling) on an NSTextView?
Thanks!
Remember that user interface elements, and this includes NSTextView, do their magic on the main thread. If you're attempting to add information to the text view, that's where you'd best be doing it. Here's how:
[[output textStorage] performSelectorOnMainThread:#selector(appendAttributedString:)
withObject:str
waitUntilDone:YES];
I'd address your third point, but frankly, that's a thing of which I'm still very much a student.
To address your fourth point, it would appear you've got that figured out; just combine your append and scroll actions. But just like changing the contents of textStorage, you want to be sure you're doing this on the main thread. Since -scrollRangeToVisible: doesn't take an object for its argument, you have to do this a bit differently:
dispatch_async(dispatch_get_main_queue(), ^{
[output scrollRangeToVisible:NSMakeRange([[output string] length], 0)];
});
My first example notwithstanding, you could place your call to -appendAttributedString: inside that block as well:
dispatch_async(dispatch_get_main_queue(), ^{
[[output textStorage] appendAttributedString:str];
[output scrollRangeToVisible:NSMakeRange([[output string] length], 0)];
});
Regarding the recommended way of appending to the NSTextView: You're doing quite well with appendAttributedString:, but it's recommended to shield it inside shouldChangeTextInRange, then a beginEditing, appendAttributedString, and finally endEditing:
textStorage = [textView textStorage];
if([textView shouldChangeTextInRange:range replacementString:string])
{
[textStorage beginEditing];
[textStorage replaceCharactersInRange:range withAttributedString:attrStr];
// or if you've already set up the attributes (see below)...
// [textStorage replaceCharactersInRange:range withString:str];
[textStorage endEditing];
}
I'd strongly suggest replacing scrollRangeToVisible: by scrollToPoint:, as scrollRangeToVisible: will cause a lot of flickering and it will also gradually become slower as you move 'down the range'.
A quick-and-dirty way could be something like this:
- (void)scrollToBottom
{
NSPoint pt;
id scrollView;
id clipView;
pt.x = 0;
pt.y = 100000000000.0;
scrollView = [self enclosingScrollView];
clipView = [scrollView contentView];
pt = [clipView constrainScrollPoint:pt];
[clipView scrollToPoint:pt];
[scrollView reflectScrolledClipView:clipView];
}
I let constrainScrollPoint do all the calculation work.
I do this, because my calculations failed anyway (those suggested by Apple and others, that used visRect/docRect coordinates, produced unreliable results).
reflectScrolledClipView is also important; it updates the scroll bar so it has the correct proportion and position.
You might also find it interesting to know when scrolling has occurred. If so, subscribe to both NSViewBoundsDidChangeNotification and NSViewFrameDidChangeNotification. When one of them occurs, the scroll bar position most likely changed (investigate [textView visibleRect] and [textView bounds]).
I see you also have trouble with the text-attributes. So did I for a long time.
I found that appending an attributed string would help quite a lot, but it still wasn't enough for the text being typed.
..Then I found out about typingAttributes.
When setting up your NSTextView, for instance in an -awakeFromNib, you can pick what you like from the following...
NSMutableParagraphStyle *paragraphStyle;
float characterWidth;
NSFont *font;
uint32_t tabWidth;
NSMutableDictionary *typingAttributes;
tabWidth = 4;
font = [NSFont fontWithName:#"Monaco" size:9.0];
paragraphStyle = [[textView defaultParagraphStyle] mutableCopy];
if(NULL == paragraphStyle)
{
paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
// or maybe:
// paragraphStyle = [NSParagraphStyle new];
}
characterWidth = [[font screenFontWithRenderingMode:NSFontDefaultRenderingMode] advancementForGlyph:(NSGlyph)' '].width;
[paragraphStyle setDefaultTabInterval:(characterWidth * (float) tabWidth];
[paragraphStyle setTabStops:[NSArray array]];
typingAttributes = [[textView typingAttributes] mutableCopy];
if(NULL == typingAttributes)
{
typingAttributes = [NSMutableDictionary new];
}
[typingAttributes setObject:paragraphStyle forKey:NSParagraphStyleAttributeName];
[typingAttributes setObject:font forKey:NSFontAttributeName];
[textView setTypingAttributes:attributes];
...It's way more than you probably need, but it shows how you can set the font, the tab width and the typing attributes.
NSForegroundColorAttributeName might also be interesting for you (as well as some other attributes, type NSForegroundColorAttributeName in Xcode and option-double-click on it, then you'll see some more attributes (you can command-double-click as well; this takes you to the definition in the header file).
Inside my custom scroll view i have added predicate object as under. It is giving error in the methods predicateWithSubpredicates in debug stack. Here is my sample code please let me know if any error are present.
-(void) awakeFromNib
{
NSPredicateEditor *predicateeditor = [[NSPredicateEditor alloc] initWithFrame:NSMakeRect(0, 0, 200, 150)];
NSArray *leftExpressions = [NSArray arrayWithObjects:[NSExpression expressionForKeyPath:#"date"], nil];
NSAttributeType rightType = NSDateAttributeType;
NSComparisonPredicateModifier modifier = NSAllPredicateModifier; //don't need "ANY" or "ALL"
NSArray *operators = [NSArray arrayWithObjects:[NSString stringWithString:#"Today"],[NSString stringWithString:#"Tomorrow"],[NSString stringWithString:#"Next week"], nil];
NSUInteger options = 0;
NSPredicateEditorRowTemplate *rowTemplate = [[NSPredicateEditorRowTemplate alloc] initWithLeftExpressions:leftExpressions rightExpressionAttributeType:rightType modifier:modifier operators:operators options:options];
[predicateeditor setRowTemplates:[NSArray arrayWithObject:rowTemplate]];
[rowTemplate release];
[self addSubview:predicateeditor];
[predicateeditor addRow:nil];
[predicateeditor displayValuesForRow:1];
[predicateeditor release];
}
As you've written it, this is going to define a predicate like this:
ALL date {"Today", "Tomorrow", "Next Week"} {a user-entered date}
I hope you can see that this is non-sensical.
For starters, if you really mean that //don't need "ANY" or "ALL", then you shouldn't be be using NSAllPredicateModifier. You should be using NSDirectPredicateModifier.
Also, the things that are allowed to go in the operators array are NSNumber objects that box one of the built-in predicate operator values.
So: what are you trying to accomplish?
PanelImage is Global allocED and initiated in a method called from ViewDidLoad
PanelImage = [[UIImageView alloc]initWithImage:[UIImage imageNamed:#"panel.png"];
[self.view addsubView:PanelImage];
My image comes up properly but
when i try to hide it using
PanelImage.hidden = YES;
it Doesn't hide
i test the property using
if(PanelImage.hidden) but i doesnt pass
i also printed it
NSLog(#"panel is hidden %d",PanelImage.hidden);
it outputs "Panel is hidden 0" even after setting it by
PanelImage.hidden = 1;
please help,atleast tell me some technique to debug it.
there are lots of methods which are using PanelImage.hidden,it used to work before 2days.now only point where PanelImage.hidden works is the custom initialization function(called from ViewDidLoad)
also this is piece of a very big code.
after lots of debugging i came to a point where PanelImage.hidden goes inoperable
PanelImage.hidden = YES;//works till here here
[self GetSymbolAttr];//wont work after this function is called
definition of GetSymbolAttr
-(void)GetSymbolAttr
{
int tmp = 0;
NSArray* PosAndSizeArrForCurrSlot = [[PosAndSizeArr objectAtIndex:SlotId] componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:#" "]];
for(NSString* values in PosAndSizeArrForCurrSlot)
PositionAndSize[tmp++] = [values intValue];
}
as you can see nothing is happening in GetSymbolAttr which will make Pattern.hidden go inoperatble
if PanelImage.hidden = YES; is now working than you can do its alpha.set to zero . PanelImage.alpha = 0 ;
try this:
UIImageView *PanelImage = [[UIImageView alloc] initWithImage:[UIImage ...]];
[self.view addsubView:PanelImage];
I didn't find initWithImageNamed method with UIImageView !
Do you set PanelImage.hidden = YES in the same metod, where you're doing UIImageView *PanelImage = [[UIImageView alloc]initWithImageNamed:#"Panel.png"];? Or haven't you class field with the same name PanelImage?