[Top][All Lists]

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: how?

From: Alexander Malmberg
Subject: Re: how?
Date: Thu, 05 Feb 2004 02:08:09 +0100

reuss wrote:
> how do I connect a textfield to a textview? I dont really understand how
> it should work, you know, I am a beginner (absolutely)
> andras

The attached example shows how to limit the length of the string in a
text field by subclassing and implementing the NSTextView delegate
method. To use it, just allocate an instance of LimitedLengthTextField
instead of NSTextField and call -setMaxLength: (defaults to 0).

Depending on what you're trying to do, more sophisticated behavior in
the delegate method may be necessary, but that shouldn't be too hard to

- Alexander Malmberg
copyright 2004 Alexander Malmberg <>

#ifndef LimitedLengthTextField_h
#define LimitedLengthTextField_h

#include <AppKit/NSTextField.h>

@interface LimitedLengthTextField : NSTextField
        int maxLength;
-(void) setMaxLength: (int)maxLength;


copyright 2004 Alexander Malmberg <>

#include "LimitedLengthTextField.h"

#include <AppKit/NSTextStorage.h>
#include <AppKit/NSTextView.h>

@implementation LimitedLengthTextField
-(void) setMaxLength: (int)ml

/* Implement the NSTextView delegate method. */
-(BOOL) textView: (NSTextView *)textView
        shouldChangeTextInRange: (NSRange)r
        replacementString: (NSString *)replacementString
        int newLength;

        /* Pure attribute changes are ok. */
        if (!replacementString)
                return YES;

        /* The exact change isn't known. Disallow the change to be safe. */
        if (r.location==NSNotFound)
                return NO;

        /* Calculate the length of the text after the change. */
        newLength=[[textView textStorage] length]+[replacementString 

        /* If it's too long, disallow the change. */
        if (newLength>maxLength)
                return NO;

        /* Otherwise, allow it. */
        return YES;


reply via email to

[Prev in Thread] Current Thread [Next in Thread]