私はTextViewを持っており、現在の単語と同じサイズと同じフォントで各単語の上にボタンを追加する必要があります。このコードは機能しますが、行に1つの単語がある場合などはありません。UITextView - 単語が行の最後の単語であることを定義する方法
.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の行の最後のものであることを定義する方法はありますか?
申し訳ありませんが動作しますが、私はあなたが何を意味するかキャッチしません。 [sourceArray count] == 0の場合、ソース文字列が空であることを意味します。そして、[sourceString count]は動作しません。 – Michael
@Michael、はい。 textViewに複数の単語が含まれている場合、それらの単語の間にスペース '@" "があり、' [sourceString componentsSeparatedByString:@ ""] 'はそれらの単語を配列として返します。しかし、textViewに1つの単語しか含まれていない場合は、テキストにスペースがないので、 '[sourceString componentsSeparatedByString:@" "]'は 'nil'を返します。したがって、 '[sourceArray count]'は '0'になります。その場合、 '[sourceString count]'が '0'でなければ、textViewに単語があります。右?これは、if文のif([sourceArray count] == 0 && [sourceString count]!= 0) 'が動作する方法です。 – EmptyStack
@EmptyStackまず、私の質問に注意を払うことに感謝します。しかし、NSStringクラスにはメソッドカウントがありません。私の質問がはっきりしていないのは私のせいです。つまり、「bla bla bla bla bla bla bla bla」のようなテキストがあれば、それは機能します。テキストが "bla bla bla bla bla bla bla bla bla \ nbla \ n bla bla"の場合 - それはしません。私はUITextViewが現在の単語で新しい行を開始したという通知を得る必要があります。 – Michael