Reputation: 6942
I have NSTextField
with placeholder. And it's binded to some integer property. So I want to display empty text in the field (with placeholder shown) when binded integer is zero.
Is it possible to do it?
(Update)
I discovered that this can be done through NSNumberFormatter
- it has —(void) setZeroSymbol: (NSString*) string
method. Not tried yet this in practice...
Upvotes: 1
Views: 1788
Reputation: 817
You could use an NSValueTransformer.
(Just in case)Create a new class, subclass from NSValueTransformer. In the implementation, add something like this:
+(Class)transformedValueClass {
return [NSString class];
}
-(id)transformedValue:(id)value {
if (value == nil) {
return nil;
} else {
if ([value integerValue] == 0) {
return @"";
} else {
return [NSString stringWithFormat:@"%d", [value stringValue]];
}
}
}
In Interface Builder, select your field, go to the bindings tab, and in the Value Transformer drop down, either select or type in your class name you made. This should prevent you from having to worry about modifying it elsewhere. I'm not 100% positive about it showing the placeholder (I don't have a Mac available right now).
EDIT: I can confirm that this does indeed work. Here is a link to a github project I made to show how to use it: https://github.com/macandyp/ZeroTransformer
Upvotes: 3
Reputation: 46533
You can not do conditional binding.
You need to create another property that will hold the value based on condition and use that property and bind to textfield.
I am using bindedString
and bindedInteger
. bindedString
is bound to text field.
Whenever some action is performed it is updated.
- (id)init{
self = [super init];
if (self) {
self.bindedString=@"place holder string";
}
return self;
}
- (IBAction)button:(id)sender {
if (self.bindedInteger==0) {
self.bindedString=@"place holder string";
}
else{
self.bindedString=[NSString stringWithFormat:@"%ld",self.bindedInteger];
}
}
Upvotes: 0
Reputation: 4712
check the integer value before binding, if you are binding at runtime. Try
int i;
if (i == 0)
{
txt.placeholder = @"text";
}
else
{
[txt setStringValue:[NSString stringWithFormat:@"%d",i]];
}
Upvotes: 0