iPhone的scrollView使用id动态添加元素
我想用很多不同的 UI 元素填充滚动视图。 因此,我想我应该编写一个方法来记住滚动视图中的当前位置,并将元素添加到滚动视图的当前位置。
像这样的事情:
- (void)addUIElement:(id)element withWidth:(CGFloat)width andHeight:(CGFloat)height andYGap:(CGFloat)YGap {
element.frame = CGRectMake(currentScrollPos.x, (currentScrollPos.y + YGap), width, height);
[scrolly addSubview:element];
//And then set the current scroll position here
}
不幸的是,当我尝试访问 element.frame = ... 时,我收到对非结构或联合中的成员的请求。当我尝试执行 [element frame] = ... 需要左值作为赋值的左操作数。
现在,首先我不确定将对象动态添加到滚动视图的最佳方法是什么。也许任何人都有更好或更简单的方法。
另一方面,我不明白为什么上面的方法不起作用?!我是否必须将我的元素投射到实际的班级中?我以为我不必这样做......而且那样我的方法就不再有意义了。或者至少需要更多步骤......
I want to populate a scrollView with quite a few different UI elements.
Therefore I thought I would write a method that remembers the current Position in the scrollView and just adds the element to the scrollView at the current Position.
Something like:
- (void)addUIElement:(id)element withWidth:(CGFloat)width andHeight:(CGFloat)height andYGap:(CGFloat)YGap {
element.frame = CGRectMake(currentScrollPos.x, (currentScrollPos.y + YGap), width, height);
[scrolly addSubview:element];
//And then set the current scroll position here
}
Unfortunately when I try to do access element.frame = ..., I get request for member in something not a structure or union. When I try to do [element frame] = ... Lvalue required as left operand of assignment.
Now, first of all I am not sure what's the best way to dynamically add objects to a scrollview. Maybe anyone has a better or easier approach.
Then on the other hand, I don't get why the above does not work?! Would I have to cast my element to the actual class? I thought I would not have to do so... Also then my method would not make that much sense anymore. Or at least would require some more steps...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为这应该有效:
但是,如果您在方法中使用不同的 UI 元素,您可以将元素参数设置为 UIView* 而不是 id 吗?这样你的代码将适用于所有 UIView 子类(我想这就是你真正需要的)
This should work I think:
However if you work with different UI elements in your method may be you can make your elements parameter UIView* instead of id? This way your code will work for all UIView subclasses (which is what you actually need I suppose)
不同之处在于“id”没有任何对框架的引用。它可以是任何东西。您想在方法声明中执行
(UIView *)element
,或者在对 element.frame 的调用中执行((UIView *)element).frame
。(是的,您放在屏幕上的所有内容都继承自
UIView
-UIButton
、UIImageView
等)The difference is that "id" doesn't have any kind of reference to a frame. It could be anything. You want to instead do
(UIView *)element
in the method declaration, or alternatively in the call to element.frame, you would do((UIView *)element).frame
.(And yeah, all things that you put on the screen are inheriting from
UIView
--UIButton
,UIImageView
, etc.)