可以引用 UITextView 或 UITextField 的指针
我想打印一个包含 UITextFields 和 UITextViews 混合的表单,无论其实际类型如何,对每个表单执行完全相同的操作。为了保持代码干净,我想将视图数组中的每个项目分配给同一个变量,以便检索其打印参数。我以为我可以用 id 类型的变量来做到这一点,但我还没有找到任何可以编译的东西。下面的代码无法编译,但它显示了我想要做的事情。我感谢任何告诉我如何正确执行此操作的人。
id theField;
//for each field on the page
for (j = offsetToFirstFormField; j < [self.fields count]; j++) {
theField = [self.fields objectAtIndex: j];
printStr = theField.text;
if ([printStr length] > 0) {
theFont = [theField font];
maxSize = CGSizeMake(theField.frame.size.width, theField.frame.size.height);
printStrSize = [printStr sizeWithFont:theFont constrainedToSize:maxSize lineBreakMode:UILineBreakModeClip];
printRect = CGRectMake((theField.frame.origin.x * xScale) + xOffset, (theField.frame.origin.y * yScale) + yOffset, printStrSize.width, printStrSize.height);
[printStr drawInRect:printRect withFont:theFont];
}
}
I want to print a form that contains a mixture of UITextFields and UITextViews, doing exactly the same thing with each one regardless of its actual type. To keep the code clean I'd like to assign each item in the views array to the same variable in order to retrieve its printing parameters. I thought I could do this with a variable of type id, but I haven't hit on anything that will compile. The code below doesn't compile but it shows what I want to do. My thanks to anyone who tells me how to do this correctly.
id theField;
//for each field on the page
for (j = offsetToFirstFormField; j < [self.fields count]; j++) {
theField = [self.fields objectAtIndex: j];
printStr = theField.text;
if ([printStr length] > 0) {
theFont = [theField font];
maxSize = CGSizeMake(theField.frame.size.width, theField.frame.size.height);
printStrSize = [printStr sizeWithFont:theFont constrainedToSize:maxSize lineBreakMode:UILineBreakModeClip];
printRect = CGRectMake((theField.frame.origin.x * xScale) + xOffset, (theField.frame.origin.y * yScale) + yOffset, printStrSize.width, printStrSize.height);
[printStr drawInRect:printRect withFont:theFont];
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您不能将点语法与
id
变量一起使用。您必须坚持消息发送语法。例如,您必须将以下内容更改为:
如果这不能解决问题,请编辑您的问题并粘贴您收到的实际错误消息。
You can't use dot-syntax with
id
variables. You have to stick with message-sending syntax. For example, you have to change this:to this:
If that doesn't fix it, edit your question and paste in the actual error messages you're getting.
将您的可打印功能封装在协议中。因此,您将使用
id
而不是id
。您的协议将具有诸如getText
getFont
之类的方法。或者您可以使用类别来扩展现有的类。Encapsulate your printable functionality in a protocol. So you will be using
id<Printable>
rather thanid
. Your protocol will have methods likegetText
getFont
. Or you can use category to extend the existing classes.