UITextView - как определить, что слово является последним словом в строке - PullRequest
0 голосов
/ 27 июня 2011

У меня есть TextView, и мне нужно добавить кнопку над каждым словом с тем же размером и тем же шрифтом заголовка кнопки, что и в текущем слове.Этот код работает, но если в строке есть одно слово, например, это не так.

.h 
@interface Text2ButtonsViewController : UIViewController {

    UITextView *sourceText;
}
@property (nonatomic, retain) IBOutlet UITextView *sourceText;

.m

-(IBAction) processText {

    for (UIView *button in [self.sourceText subviews]) {
        if (button.tag == 33) 
            [button removeFromSuperview];
    }

    NSString *sourceString = [NSString stringWithString:self.sourceText.text];

    NSArray *sourceArray = [sourceString componentsSeparatedByString:@" "];

    CGSize spaceSize = [@" " sizeWithFont:self.sourceText.font];

    float textPadding = 8.0f;

    float stepX = textPadding;
    float stepY = textPadding;
    CGRect buttonFrame;

    for (NSString *string in sourceArray) {

    UIButton *actButton = [UIButton buttonWithType:UIButtonTypeCustom];

    actButton.backgroundColor  = [[UIColor greenColor] colorWithAlphaComponent:0.5];

    [actButton setTitle:string forState:UIControlStateNormal];
    actButton.titleLabel.font = self.sourceText.font;
    CGSize stringSize = [string sizeWithFont:self.sourceText.font];
    actButton.tag = 33;
    //if summary width of all buttons and spaces are greater than 
    if (stepX + stringSize.width + textPadding > self.sourceText.frame.size.width) {
        stepX = textPadding;
        stepY = stepY + stringSize.height;
    }
    buttonFrame = CGRectMake(stepX, stepY, stringSize.width, stringSize.height);

    stepX = stepX + stringSize.width + spaceSize.width;
    actButton.frame = buttonFrame;

    [self.sourceText addSubview:actButton];

    }

}

Как определить, что слово является последним в строке UITextView?

Ответы [ 2 ]

1 голос
/ 27 июня 2011

Здесь необходимо выполнить простую проверку условий.

NSArray *sourceArray = [sourceString componentsSeparatedByString:@" "];

if ([sourceArray count] == 0 && [sourceString length] != 0) {

    sourceArray = [NSArray arrayWithObject:sourceString];
}

Редактировать:

TextView будет содержать как пробел, так и символы новой строки.Таким образом, вы можете использовать метод componentsSeparatedByCharactersInSet: для разделения текста.Просто используйте,

NSArray *sourceArray = [sourceString componentsSeparatedByCharactersInSet:[NSCharacterSet whiteSpaceAndNewLineCharacterSet]];

Надеюсь, это должно сработать.

0 голосов
/ 29 июня 2011

Этот код у меня работает



@interface DetailViewController : UIViewController {

    UITextView *sourceText;
    UIView *buttonHolder;
}

@implementation DetailViewController

- (IBAction) processText {

    self.buttonHolder.hidden = NO;

    self.sourceText.editable = NO;

    self.buttonHolder.frame = CGRectMake(0.0f, 0.0f, self.sourceText.contentSize.width, self.sourceText.contentSize.height); 

    NSLog(@"self.buttonholder.frame = %@", NSStringFromCGRect (self.buttonHolder.frame) );

    if ([[self.buttonHolder subviews] count] !=0) {
        for (UIView *button in [self.buttonHolder subviews]) 
            [button removeFromSuperview];

    }

    CGSize spaceSize = [@" " sizeWithFont:self.sourceText.font];

    float textPadding = 8.0f;

    float stepX = textPadding;
    float stepY = textPadding;
    CGRect buttonFrame;
    CGSize wordSize;
    NSString *sourceString = [NSString stringWithString:self.sourceText.text];

    float lineHeight = [sourceString sizeWithFont:self.sourceText.font].height;

    NSArray *linesArray = [sourceString componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];

    for (NSString *line in linesArray) {

        NSArray *wordsInLine = [line  componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];

        for (NSString *word in wordsInLine) {

            UIButton *actButton = [UIButton buttonWithType:UIButtonTypeCustom];

            actButton.backgroundColor  = [[UIColor greenColor] colorWithAlphaComponent:0.5];

            [actButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];

            [actButton setTitleColor:[UIColor redColor] forState:UIControlStateHighlighted];

            [actButton setTitle:word forState:UIControlStateNormal];

            [actButton addTarget:self action:@selector(workWithWord:) forControlEvents:UIControlEventTouchUpInside];

            actButton.titleLabel.font = self.sourceText.font;

            wordSize = [word sizeWithFont:self.sourceText.font];
            actButton.tag = 33;

            if (stepX + wordSize.width + textPadding > self.sourceText.frame.size.width) {
                stepX = textPadding;
                stepY = stepY + lineHeight;
            }

            buttonFrame = CGRectMake(stepX, stepY, wordSize.width, lineHeight-lineHeight/10.0);
            actButton.frame = buttonFrame;

            stepX = stepX + wordSize.width + spaceSize.width;

            [self.buttonHolder addSubview:actButton];

        }

        stepX = textPadding;
        stepY = stepY + lineHeight;

    }

}

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...