【发布时间】:2012-01-31 05:38:44
【问题描述】:
我在界面顶部(状态栏下方)有一个 uiview,只显示了它的底部。
实际上,我想让红色的uiview向下滑动以完全通过拖动显示,例如本机iOS中的通知中心,而不仅仅是点击按钮。
我应该使用什么来“触摸并下拉”uiview,以便它可以完全显示?
【问题讨论】:
标签: iphone ios ipad uinavigationcontroller uitabbarcontroller
我在界面顶部(状态栏下方)有一个 uiview,只显示了它的底部。
实际上,我想让红色的uiview向下滑动以完全通过拖动显示,例如本机iOS中的通知中心,而不仅仅是点击按钮。
我应该使用什么来“触摸并下拉”uiview,以便它可以完全显示?
【问题讨论】:
标签: iphone ios ipad uinavigationcontroller uitabbarcontroller
无需寻找拖放的解决方法。 UIScrollView 可以做到这一点,而不会因监听触摸而带来任何性能损失。
@interface PulldownView : UIScrollView
@end
@implementation PulldownView
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (!self) {
return self;
}
self.pagingEnabled = YES;
self.bounces = NO;
self.showsVerticalScrollIndicator = NO;
[self setBackgroundColor:[UIColor clearColor]];
double pixelsOutside = 20;// How many pixels left outside.
self.contentSize = CGSizeMake(320, frame.size.height * 2 - pixelsOutside);
// redArea is the draggable area in red.
UIView *redArea = [[UIView alloc] initWithFrame:frame];
redArea.backgroundColor = [UIColor redColor];
[self addSubview:redArea];
return self;
}
// What this method does is to make sure that the user can only drag the view from inside the area in red.
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event
{
if (point.y > height)
{
// Leaving useless touches to the views under it.
return nil;
}
return [super hitTest:point withEvent:event];
}
@end
使用方法:
1. 初始化一个 PulldownView 的实例。
2. 使用 [addSubview:] 将您想要显示的任何内容添加到实例中。
3. 隐藏红色区域。
[pulldownView setContentOffset:CGPointMake(0, heightOfTheView - pixelsOutside)];
这是一个简单的例子。您可以为其添加任何功能,例如在可拖动区域的底部添加一个带标题的按钮栏以实现 click-n-drop,或者向界面添加一些方法以由调用者重新定位它。
【讨论】:
创建UIView 的子类。
覆盖touchesBegan:withEvent 和touchesMoved:withEvent。
在touchesBegan 中可能进行视觉更改,以便用户知道他们正在触摸视图。
在 touchesMoved 中使用
[[touches anyObject] locationInView:self]
和
[[touches anyObject] previousLocationInView:self]
计算当前触摸位置和最后触摸位置之间的差异(检测向下拖动或向上拖动)。
如果你是自定义绘图,调用[self setNeedsDisplay] 告诉你的视图在它的drawRect:(CGRect)rect 方法中重绘。
注意:这假设此视图不使用多点触控。
【讨论】:
参考我在iPhone App: implementation of Drag and drop images in UIView的回答
您只需要使用TouchesBegin 和TouchesEnded 方法。在那个例子中,我已经展示了如何使用CGPoint,而不是你必须尝试使用setFrame 或drawRect 作为你的视图。
一旦调用TouchesMoved 方法,您就必须使用setFrame 或drawRect(不确定,但哪个有效,主要是setFrame)也从CGPoint 获取高度。
【讨论】: