ios - 如何通过从边缘拖动来调整 UIView 的大小?

标签 ios uiview resize

在我的 iPad 应用程序中,我希望用户能够通过从其边缘拖动 View 来调整 UIView 的大小。我将使用 iOS 5 SDK,那么最简洁的方法是什么?有没有其他方法可以在不处理 touchesBegan、touchesMoved 等的情况下实现这一目标?

最佳答案

您可以通过检查触摸起点来做到这一点。如果它击中了您的四个角之一,您可以根据该触摸起点和当前触摸点之间的距离调整大小。 (如果触摸起点没有碰到角落,我们只是移动 View 而不是调整大小。)

定义可拖动角的大小。

CGFloat kResizeThumbSize = 45.0f;

将这些实例变量添加到您的类中以跟踪触摸状态以及我们调整大小的方式。

@interface MY_CLASS_NAME : UIView {
    BOOL isResizingLR;
    BOOL isResizingUL;
    BOOL isResizingUR;
    BOOL isResizingLL;
    CGPoint touchStart;
}

处理触摸开始/改变事件。

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [[event allTouches] anyObject];
    touchStart = [[touches anyObject] locationInView:self];
    isResizingLR = (self.bounds.size.width - touchStart.x < kResizeThumbSize && self.bounds.size.height - touchStart.y < kResizeThumbSize);
    isResizingUL = (touchStart.x <kResizeThumbSize && touchStart.y <kResizeThumbSize);
    isResizingUR = (self.bounds.size.width-touchStart.x < kResizeThumbSize && touchStart.y<kResizeThumbSize);
    isResizingLL = (touchStart.x <kResizeThumbSize && self.bounds.size.height -touchStart.y <kResizeThumbSize);
}

 - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    CGPoint touchPoint = [[touches anyObject] locationInView:self];
    CGPoint previous = [[touches anyObject] previousLocationInView:self];

    CGFloat deltaWidth = touchPoint.x - previous.x;
    CGFloat deltaHeight = touchPoint.y - previous.y;

    // get the frame values so we can calculate changes below
    CGFloat x = self.frame.origin.x;
    CGFloat y = self.frame.origin.y;
    CGFloat width = self.frame.size.width;
    CGFloat height = self.frame.size.height;

    if (isResizingLR) {
        self.frame = CGRectMake(x, y, touchPoint.x+deltaWidth, touchPoint.y+deltaWidth);
    } else if (isResizingUL) {
        self.frame = CGRectMake(x+deltaWidth, y+deltaHeight, width-deltaWidth, height-deltaHeight);
    } else if (isResizingUR) {
        self.frame = CGRectMake(x, y+deltaHeight, width+deltaWidth, height-deltaHeight);      
    } else if (isResizingLL) {
        self.frame = CGRectMake(x+deltaWidth, y, width-deltaWidth, height+deltaHeight);   
    } else {
        // not dragging from a corner -- move the view
        self.center = CGPointMake(self.center.x + touchPoint.x - touchStart.x,
            self.center.y + touchPoint.y - touchStart.y);
    }
} 

关于ios - 如何通过从边缘拖动来调整 UIView 的大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8460119/

相关文章:

ios - 使用 AFNetworking 2.0 管理缓存图像

ios - 嵌入容器中的 UITableView 不刷新

ios - UIView 不会垂直滚动到 UIScrollView 内

javascript - 如何在页面加载前调整布局

java - Primefaces 数据表 - 更改字体大小

Java MigLayout 在行中固定等宽

ios - 为什么使用 POST 参数的这个成功的 Swift 异步调用没有返回预期的内容

iphone - 初始化时类型不兼容?

ios - 在 UIView 容器中添加 bezierpath

ios - 如何在 Objective C 中检查 UIView 是否为零