如何循环遍历子视图以获取NSTextViews的文本 [英] How to loop through subviews in order to get the text of NSTextViews

查看:743
本文介绍了如何循环遍历子视图以获取NSTextViews的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个NSView包含NSTextView的几个实例。
我想获得每个实例的内容(字符串)。
到目前为止,我有这个(这段代码不编译):

  subviews]){
NSLog(@class:%@,[view className]);
if([view isKindOfClass:[NSTextView class]])
NSLog(@[view string]%@,[view string]);}

此时,我希望能够将字符串消息发送到 view 这是NSTextView的一个实例,但是:



错误信息: '

解决方案

你可能只是做一个简单的转换来获得编译器的接受。您可以使用局部变量或更复杂的内联转型来执行此操作:

  ]){
NSLog(@class:%@,[view className]);
if([view isKindOfClass:[NSTextView class]]){
NSTextView * thisView =(NSTextView *)view;
NSLog(@[view string]%@,[thisView string]);
}
}

  for(NSView * view in [self subviews]){
NSLog(@class:%@,[view className]);
if([view isKindOfClass:[NSTextView class]])
NSLog(@[view string]%@,[(NSTextView *)view string]
}

编辑:我会提到我们所说的Duck Typing可能会考虑询问对象是否响应你想要发送的选择器,而不是如果它是你期望的类(如果它像鸭子,它是一个鸭子...)。

  for(NSView * view in [self subviews]){
NSLog(@class:%@,[view className]);
if([view respondingToSelector:@selector(string)]){
NSLog(@[view string]%@,[view performSelector:@selector(string)]);
}
}


I have a NSView which contains several instances of NSTextView. I would like to get the content (string) of each instance. So far, I have this (this code does not compile) :

for(NSView *view in [self subviews]) {
    NSLog(@"class: %@ ", [view className]);
if([view isKindOfClass:[NSTextView class]])
    NSLog(@"[view string] %@",[view string]);}

At this point, I expect to be able to send the string message to view which is an instance of NSTextView, but:

Error message: No visible @interface for 'NSView' declares the selector 'string'

Where is my error ?

解决方案

You can probably just do a simple cast to get the compiler's acceptance. You can do it with either a local variable, or a more complicated inline cast:

for(NSView *view in [self subviews]) {
  NSLog(@"class: %@ ", [view className]);
  if([view isKindOfClass:[NSTextView class]]) {
    NSTextView *thisView = (NSTextView *)view;
    NSLog(@"[view string] %@",[thisView string]);
  }
}

or

for(NSView *view in [self subviews]) {
  NSLog(@"class: %@ ", [view className]);
  if([view isKindOfClass:[NSTextView class]])
    NSLog(@"[view string] %@",[(NSTextView *)view string]);
}

EDIT: I wil mention what we call "Duck Typing"... You might consider asking the object if it responds to the selector you want to send, instead of if it's the class you expect (if it quacks like a duck, it is a duck...).

for(NSView *view in [self subviews]) {
  NSLog(@"class: %@ ", [view className]);
  if([view respondsToSelector:@selector(string)]) {
    NSLog(@"[view string] %@",[view performSelector:@selector(string)]);
  }
}

这篇关于如何循环遍历子视图以获取NSTextViews的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆