【问题标题】:How do I make my UIView retractable when I add it as a subview to a scrollView?当我将 UIView 作为子视图添加到 scrollView 时,如何使 UIView 可伸缩?
【发布时间】:2020-12-06 22:20:56
【问题描述】:

我正在制作一个只显示个别日子的日历样式应用程序,所以我现在有一个从午夜开始到午夜结束的每一天的滚动视图,我希望能够在每一天点击并创建“事件” .

到目前为止,我已经能够在每次点击屏幕时创建 UIView,但现在我试图在点击它们时对其进行编辑。

这是我的 ViewDidLoad 中用于创建事件的一些代码:

 let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(tapped(gestureRecognizer:)))
    scrollView.addGestureRecognizer(tapRecognizer)
    tapRecognizer.delegate = self

这是我在点击的函数中的代码:

@objc func tapped(gestureRecognizer: UITapGestureRecognizer) {
    let tapLocation = gestureRecognizer.location(in: scrollView)
    let eventLength = 100
    let eventLocation = CGPoint(x: tapLocation.x, y: tapLocation.y-CGFloat(eventLength/2))
    
    //Creates Rectangle event
    let eventRect = CGRect(x: 0, y: Int(eventLocation.y), width: Int(view.frame.size.width), height: (eventLength))
    let testEventView = UIView(frame: eventRect)
    testEventView.backgroundColor = UIColor(hue: 0.5667, saturation: 0.58, brightness: 0.89, alpha: 1.0)
    self.scrollView.addSubview(testEventView)
    
}

但是现在,我如何识别我何时点击每个事件,并根据我点击的事件更改它们。就像我正在考虑在 UIView 上添加一个文本框并在您点击文本框时对其进行编辑,但我不确定如何制作它,以便应用程序知道我何时点击每个事件与整个 scrollView。

抱歉,这个问题冗长而开放,但如果有人能指出我要查找的内容的正确方向,或者可能不使用 UIView,或者任何可以帮助我完成此事件创建的东西,都会有所帮助!谢谢!

【问题讨论】:

  • 很确定这会自然发生。您是否尝试将其构建出来看看? UITextView 会自动响应点击,所以不需要为此添加另一个手势识别器。如果是子视图,UIScrollView 应该忽略那里的点击。

标签: ios swift xcode object calendar


【解决方案1】:

首先,您可以为每个事件视图添加点击手势

testEventView.addGestureRecognizer(UITapGestureRecognizer(target: self,
                                                          action: #selector(eventViewTapped(gestureRecognizer:))))

self.scrollView.addSubview(testEventView)

然后,在 action 中,您可以检索事件视图

@objc func eventViewTapped(gestureRecognizer: UITapGestureRecognizer) {
    let eventView = gestureRecognizer.view

在你必须确定它是哪个事件视图之后。 有很多方法可以做到,例如

  1. 将 eventViews 存储为数组,然后从该数组中找到所选视图的对应索引
  2. tapped 函数中将标签设置为eventView,在eventViewTapped 中检索标签
  3. 使用一些自定义 UI 和数据模型,它包含有关事件视图的所有信息,就像 uitableview 一样

【讨论】:

  • @KylanO'Connor 很高兴听到这个消息!如果解决了您的问题,请将我的问题标记为正确。
猜你喜欢
  • 2014-02-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多