【问题标题】:UILabel with UIButton like glow on touch带有 UIButton 的 UILabel 就像触摸时发光
【发布时间】:2011-12-08 23:49:56
【问题描述】:

我有一个动态创建的标签列表,我为每个标签使用GestureRecognizer 来检测触摸/点击它们。我无法使用UIButton,因为我想将每个标签独有的文本传递给触摸事件处理程序,而UIButton 不允许将文本作为userinfo 传递。我不能使用UIButton.tag 传递附加信息。

现在我想要UIButton 在我的UIlabel 上的触摸发光效果。如果有其他方法可以通知用户标签被触摸,那也可以。我正在考虑使用某种快速动画或抖动效果。有什么想法或解决方法吗?

提前致谢。

【问题讨论】:

    标签: iphone ios uibutton uilabel uigesturerecognizer


    【解决方案1】:

    为什么不以编程方式创建按钮并将按钮类型设为自定义。像这样 -

    UIButton *sampleButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [sampleButton setBackgroundImage:[[UIImage imageNamed:@"redButton.png"] stretchableImageWithLeftCapWidth:10.0 topCapHeight:0.0] forState:UIControlStateNormal];
    [sampleButton setTitle:@"My Button"];
    [sampleButton addTarget:self action:@selector(buttonPressed) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:sampleButton];
    

    这里我们定义了按钮应该是什么样子UIControlStateNormal。您可以定义 UIControlStateHighlighted 的外观。

    我想说的是,使用 uibuttons 你可以得到你需要的东西。不必使用 uilabels。

    【讨论】:

    • 我现在使用的是 UIButton,而不是 UILabel。由于我无法使用 UIButton 的 addTarget 消息传递额外参数,因此我现在维护一个 UIButton.tag 映射到按下按钮时所需的附加信息。现在似乎可以工作,我可以使用 UIButton 的所有功能。
    • 好的,但是如果你想让一个 uilabel 表现得像一个 uibutton。那么最好使用uibutton!无论如何,只要它有效......很高兴我可以分享我所知道的......
    【解决方案2】:

    斯威夫特 4

    1- 使用动画创建 UIView 扩展

    2- 在文本字段、按钮、视图(UIView 的任何子类)上使用它

    UIView 扩展

    import UIKit
    
    extension UIView{
        enum GlowEffect:Float{
            case small = 0.4, normal = 1, big = 5
        }
    
        func doGlowAnimation(withColor color:UIColor, withEffect effect:GlowEffect = .normal) {
            layer.masksToBounds = false
            layer.shadowColor = color.cgColor
            layer.shadowRadius = 0
            layer.shadowOpacity = effect.rawValue
            layer.shadowOffset = .zero
    
            let glowAnimation = CABasicAnimation(keyPath: "shadowRadius")
            glowAnimation.fromValue = 0
            glowAnimation.toValue = 1
            glowAnimation.beginTime = CACurrentMediaTime()+0.3
            glowAnimation.duration = CFTimeInterval(0.3)
            glowAnimation.fillMode = kCAFillModeRemoved
            glowAnimation.autoreverses = true
            glowAnimation.isRemovedOnCompletion = true
            layer.add(glowAnimation, forKey: "shadowGlowingAnimation")
        }
    }
    

    使用方法:

    //Button
    button.doGlowAnimation(withColor: UIColor.red, withEffect: .big)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-09-05
      • 1970-01-01
      • 1970-01-01
      • 2017-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多