可以通过IB为UITextView分配变量名吗?

时间:2012-01-05 02:13:03

标签: objective-c ios uitextview

我正在开发一个应用程序,它有多个UITextView s,带有自定义键盘,然后是一些自定义菜单选项,可插入预定义文本。有没有办法将变量用于UITextView

以下代码效果很好,但我需要使用自定义键盘/按钮而不只是一个UITextView

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

我还会textView2textView3

1 个答案:

答案 0 :(得分:0)

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

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

[textViews release];

修改

如果您想知道哪个textView启动了该操作(假设您将多个textView连接到同一个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"];
                }
            }
    }
}