How to stop warning for UIView may not respond to selector

岁酱吖の 提交于 2019-12-08 16:19:40

问题


I have a class that has a UIView as a property. Sometimes I pass in a UILabel; sometimes a UITextField. No matter which I pass in, I want the class to set the text. Currently I am doing this, which works:

if ([self.viewToUpdate respondsToSelector:@selector(setText:)] && !self.newAnswer)
    [self.viewToUpdate setText:[[self.choices objectAtIndex:indexPath.row] text]];

The problem is, this gives a warning, because even though I'm checking respondsToSelector, Xcode doesn't know that my UIView will respond to setText:. How can I remove this warning?

I know that I can specifically check to see if it's a TextField or a Label, and then cast to a TextField or a Label, respectively, but this would be a pain, and if I ever have more types of views, I'd have to add a few more lines of code for each one.

I thought about creating my own protocol, and then having my class have id as the type for viewToUpdate... but of course UITextField and UILabel wouldn't conform to that protocol...


回答1:


try just casting it as an id:

if ([self.viewToUpdate respondsToSelector:@selector(setText:)] && !self.newAnswer)
    [(id)self.viewToUpdate setText:[[self.choices objectAtIndex:indexPath.row] text]];


来源:https://stackoverflow.com/questions/4340888/how-to-stop-warning-for-uiview-may-not-respond-to-selector

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!