Swift:如何通过按住按钮来逐步调整UIView的大小

时间:2016-03-04 13:27:57

标签: ios swift uiview uibutton

在我的应用程序中,用户需要根据重新调整大小的方向,通过按几次按钮来重新调整拍摄对象上的UIView以使它们组合在一起。见这个截图:

enter image description here

当前要求用户按下"加"按钮很多次,直到所需的大小,但我希望按钮通过简单地按下按钮来逐步调整UIView的大小,就好像一个线程被启动,例如每秒增加UIView 1}}直到按钮被释放。我怎么能在Swift中这样做?我要创建线程(如果是,如何)?我应该使用长按手势识别器吗?

1 个答案:

答案 0 :(得分:3)

您可以使用NSTimer创建自定义按钮以检测按下按钮。我没有测试它,但我想它可以帮助你:

public partial class ApplicationMappingsProfile
{
    private void RegisterMappings()
    {
        CreateMap<Application, AppDto>()
            .ConvertUsing<ApplicationTypeConverter>();
    }
}

private class ApplicationTypeConverter : ITypeConverter<App, AppDto>
{
    public AppDto Convert(ResolutionContext context)
    {
        var src = context.SourceValue as App;
        if (src == null)
        {
            return null;
        }

        var dto = Mapper.Map<App, AppDto>(src);
        dto.property = context.Engine.Mapper.Map.Map<Property>(src.SomeProperty);

        return result;
    }
}

您可以这样使用:

class CustomButton: UIButton {

    let updateInterval = 0.1
    var timer: NSTimer?
    var isUserPressing = false
    var updateBlock: (() -> Void)?

    convenience init() {
        self.init(frame: CGRect.zero)
    }

    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        startTimer()
    }

    override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
        stopTimer()
    }

    override func touchesCancelled(touches: Set<UITouch>?, withEvent event: UIEvent?) {
        stopTimer()
    }

    private func startTimer() {
        isUserPressing = true
        timer = NSTimer(timeInterval: updateInterval, target: self, selector: "timerUpdated", userInfo: nil, repeats: true)
        NSRunLoop.mainRunLoop().addTimer(self.timer!, forMode: NSDefaultRunLoopMode)
    }

    private func stopTimer() {
        isUserPressing = false
        timer?.invalidate()
        timer = nil
        timerUpdated() // to detect taps
    }

    private func timerUpdated() {
        updateBlock?()
    }

}