美文网首页
可拖动的label

可拖动的label

作者: CN_HarrySun | 来源:发表于2018-04-19 16:43 被阅读21次
//
//  DragLabel.swift
//
//  Created by 浩哥 on 2018/4/18.
//  Copyright © 2018年 HarrySun. All rights reserved.
//

import UIKit

class DragLabel: UILabel {

    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesMoved(touches, with: event)
        let touch = touches.first
        let current =  touch?.location(in: self)
        let previous = touch?.previousLocation(in: self)
        var center = self.center
        guard let currentX = current?.x,
            let currentY = current?.y,
            let previousX = previous?.x,
            let previousY = previous?.y else {
                return
        }
        
        center.x += CGFloat(currentX - previousX)
        center.y += CGFloat(currentY - previousY)
        
        // 控制控件的可拖动范围
        if let superview = self.superview, frame.origin.x < superview.bounds.origin.x {
            center.x = frame.size.width / 2
        }
        if let superview = self.superview, frame.origin.x > superview.bounds.size.width - frame.size.width {
            center.x = superview.bounds.size.width - frame.size.width / 2
        }
        if let superview = self.superview, frame.origin.y < superview.bounds.origin.y {
            center.y = frame.size.height / 2
        }
        if let superview = self.superview, frame.origin.y > superview.bounds.size.height - frame.size.height - 20 {
            center.y = superview.bounds.size.height - frame.size.height / 2 - 20
        }
        
        self.center = center
    }
}

相关文章

  • 可拖动的label

  • Lesson 1

    1.认识到了Object Library,其中的Label,Button,可以拖动控件到Main.storyboa...

  • 可拖动的View

    使用动画实现View的拖动 重写View中onTouchEvent方法,通过getRawX()和getRawY()...

  • 可拖动的button

    根据拖动手势的实时位置实现可拖动的button代码如下: demo地址:https://github.com/so...

  • 可拖动盒子

    发现很多都写得比较模糊,对于这个。我还是系统的总结一下。 结果是这个图片 1.我们先得进行观察 拖拽行为一共触发了...

  • H5拖拽元素

    为了让元素可拖动,需要设置元素的draggable=true属性。链接和图片默认是可拖动的,不需要 draggab...

  • android进度条seekbar自定义样式

    SeekBar是ProgressBar的扩展,在其基础上增加了一个可拖动的thumb(注:就是那个可拖动的图标)。...

  • 拖动属性draggable

    一个奇怪的现象:代码如下,设置div是可拖动的,拖动div时会触发dragStart事件 奇怪的现象如下:当拖动a...

  • iOS可拖动的View

    有时间了来整理一下一些小工具。 之前没事的时候做了一个Demo,能够轻松实现可拖动的视图。DraggableVie...

  • 可拖动排序的GridView

    http://blog.csdn.net/xiaanming/article/details/17718579 这...

网友评论

      本文标题:可拖动的label

      本文链接:https://www.haomeiwen.com/subject/hhnwkftx.html