0

I have two text fields: one for width and one for height.

Let's say the starting values are 1080 by 720. If the user changes the 720 to 360 I want to automatically change the 1080 to 540.

What is the best way to do that?

paulmelnikow
  • 16,895
  • 8
  • 63
  • 114
Anand
  • 35
  • 1
  • 8
  • I removed the second half of your question, about constraining text fields to even numbers. I'd suggest subclassing NSNumberFormatter – but would you please post that as a separate question? – paulmelnikow Mar 14 '13 at 00:21

2 Answers2

1

Add a number formatter to your nib, and configure it to limit the fields to integer values, and specify your controller as the delegate for both text fields.

You'll also need to fill in the initial values and update the text fields when you display the view. This version is based on NSPopoverDelegate but you can adapt it.

@property (assign) NSUInteger width;
@property (assign) NSUInteger height;

-(void)awakeFromNib {
    self.numberFormatter.minimumFractionDigits = 0;
    self.numberFormatter.maximumFractionDigits = 0;
}

-(void)popoverWillShow:(NSNotification *)notification {
    self.width = ___;
    self.height = ___;
    self.widthField.stringValue = @"";
    self.heightField.stringValue = @"";
}

-(void)controlTextDidChange:(NSNotification *)obj {
    NSTextField *sender = obj.object;
    NSTextView *textView = [obj.userInfo objectForKey:@"NSFieldEditor"];
    NSString *stringValue = textView.string;
    NSNumber *numberValue = [self.numberFormatter numberFromString:stringValue];
    if (!stringValue.length || !numberValue) {
        self.resizeButton.enabled = NO;
    } else {
        NSInteger integerValue =
        [[self.numberFormatter numberFromString:stringValue] integerValue];
        if (self.widthField == sender) {
            self.heightField.integerValue =
            self.height * integerValue / self.width;
        } else if (self.heightField == sender) {
            self.widthField.integerValue =
            self.width * integerValue / self.height;
        }
        self.resizeButton.enabled = YES;
    }
}
paulmelnikow
  • 16,895
  • 8
  • 63
  • 114
0

For the first question just calculate the ratio (divide one by the other): 1080 is 1.5 times 720 so if the user changes 720 to 360 just do 360*1.5 to get the value (and vice versa 540/1.5 to get the value in place of 720 if the user had changed 1080).

There is no embedded option to have NSTextField only take even numbers.