2012-01-05 63 views
1

我正在研究一个应用程序,它具有多个UITextView s自定义键盘,然后一些自定义菜单选项将插入预定义的文本。有没有办法为UITextView使用变量?UITextView可以通过IB分配一个变量名吗?

下面的代码很好用,但我需要使用自定义键盘/按钮不止一个UITextView

- (IBAction)textBTN:(id)sender { 
    textView1.text = [textView1.text stringByAppendingString:@"myAsciiString"]; 
} 

我也会有textView2textView3

回答

0

您可以添加文本字段到一个数组,在一个循环中修改其属性:

NSArray *textViews= [NSArray arrayWithObjects:textView1, textView2, textView3, nil]; 
for(UITextView *txtView in textViews) 
    txtView.text = [txtView.text stringByAppendingString:@"myAsciiString"]; 

[textViews release]; 

编辑

如果你想知道哪个textView发起了动作(假设你连接了多个textViews相同的IBAction为),你既可以设定和查看视图的标签,或者你可以用一个实例进行比较:

textView1.tag = 0; 
textView2.tag = 1; 
textView3.tag = 2; 
//etc. 

- (IBAction)someTextViewAction:(id)sender { 
    //Option 1 
    if (sender.tag == 0) 
     textView1.text = [textView1.text stringByAppendingString:@"myAsciiString"]; 
    else if(sender.tag == 1) 
     textView2.text = [textView2.text stringByAppendingString:@"myAsciiString"]; 
    else if(sender.tag == 2) 
     textView3.text = [textView3.text stringByAppendingString:@"myAsciiString"]; 

    //Option 2 
    if ([sender isEqual:textView1]) 
     textView1.text = [textView1.text stringByAppendingString:@"myAsciiString"]; 
    else if ([sender isEqual:textView2]) 
     textView2.text = [textView2.text stringByAppendingString:@"myAsciiString"]; 
    else if ([sender isEqual:textView3]) 
     textView3.text = [textView3.text stringByAppendingString:@"myAsciiString"]; 

} 

如果你想分配一个值到活动文本视图,你可以遍历你的子视图,如果它有第一响应者,设置值:

- (IBAction)someButtonAction:(id)sender { 

    for (UIView *view in self.subviews) 
    { 
      if ([view isKindOfClass:[UITextView class]]) 
      { 
       if ([view isFirstResponder]) 
       { 
         view.text = [view.text stringByAppendingString:@"myAsciiString"]; 
       } 
      } 
    } 
} 
+0

感谢您的快速回复,但这会将我的文本值同时添加到所有视图。也许我应该说我的问题有点不同。 我希望能够知道哪些UITextView被点击进行编辑,并使用上面列出的IBAction插入文本“仅在活动文本视图中”,而不是全部插入。再次感谢! – Dan 2012-01-05 02:56:53

+0

已更新,以反映您的评论。 – Jeremy 2012-01-05 03:14:43

+0

此方法(选项1)仍然评估为true,并同时将我的文本插入到所有文本视图中。我已将操作连接到IB中的一个按钮,该按钮应插入基于活动文本视图的文本。我很感激你的帮助,但我必须在你的指导中遗漏一些东西。 – Dan 2012-01-05 03:32:18

相关问题