Добавление эффекта свечения в UIButton - iOS - программирование
Подтвердить что ты не робот

Добавление эффекта свечения в UIButton - iOS

У меня есть UIButton, который является логотипом. Эта кнопка логотипа будет светиться вечно, но перестанет светиться прикосновением. Это похоже на сияющую анимацию.

Есть ли какие-либо предложения?

  Undefined symbols for architecture i386:
 "_OBJC_CLASS_$_CABasicAnimation", referenced from:
 objc-class-ref in UIView+Glow.o
 "_OBJC_CLASS_$_CAMediaTimingFunction", referenced from:
  objc-class-ref in UIView+Glow.o
  "_kCAMediaTimingFunctionEaseInEaseOut", referenced from:
  -[UIView(Glow) startGlowing] in UIView+Glow.o
   ld: symbol(s) not found for architecture i386
   clang: error: linker command failed with exit code 1 (use -v to see invocation)
4b9b3361

Ответ 2

Мне нравится эта свечение + расти/уменьшать анимацию для моих дополнительных кнопок:

-(void)makeViewShine:(UIView*) view
{
view.layer.shadowColor = [UIColor yellowColor].CGColor;
view.layer.shadowRadius = 10.0f;
view.layer.shadowOpacity = 1.0f;
view.layer.shadowOffset = CGSizeZero;


[UIView animateWithDuration:0.7f delay:0 options:UIViewAnimationOptionAutoreverse | UIViewAnimationCurveEaseInOut | UIViewAnimationOptionRepeat | UIViewAnimationOptionAllowUserInteraction  animations:^{

    [UIView setAnimationRepeatCount:15];

    view.transform = CGAffineTransformMakeScale(1.2f, 1.2f);


} completion:^(BOOL finished) {

    view.layer.shadowRadius = 0.0f;
    view.transform = CGAffineTransformMakeScale(1.0f, 1.0f);
}];

}

Ответ 3

Световой код, взятый из: Создание эффекта свечения для UILabel и UIButton

Сначала вам нужно будет импортировать QuartzCore Framework:

#import <QuartzCore/QuartzCore.h>

Когда вы создаете кнопку (или в viewDidLoad, зависит от структуры кода), добавьте этот код:

UIColor *color = button.currentTitleColor;
button.titleLabel.layer.shadowColor = [color CGColor];
button.titleLabel.layer.shadowRadius = 4.0f;
button.titleLabel.layer.shadowOpacity = .9;
button.titleLabel.layer.shadowOffset = CGSizeZero;
button.titleLabel.layer.masksToBounds = NO;

Вам понадобятся два события: UIControlEventTouchDown и UIControlEventTouchUpInside

В обработчике UIControlEventTouchDown вы добавите код:

UIColor *color = [UIColor clearColor];
button.titleLabel.layer.shadowColor = [color CGColor];

И в обработчике UIControlEventUpInside вы добавите код:

UIColor *color = button.currentTitleColor;
button.titleLabel.layer.shadowColor = [color CGColor];

Снова детали реализации зависят от того, создаете ли вы кнопку programmatical или через Interface Builder, но я уверен, что вы сможете понять это здесь.

EDIT: для пользовательской кнопки просто нужно добавить следующий код:

[button setImage:[UIImage imageNamed:@"buttonWithGlow.png"]
        forState:UIControlStateNormal];
[button setImage:[UIImage imageNamed:@"buttonWithNoGlow.png"] 
        forState:UIControlStateHighlighted];

Ответ 4

Swift 4

1- Создание расширения UIView с анимацией

2- Используйте его для текстовых полей, кнопок, представлений (любой подкласс UIView)

Примечание: вы можете изменить значения и поиграть, чтобы получить нужный эффект.

Расширение UIView

import UIKit

extension UIView {
    enum GlowEffect: Float {
        case small = 0.4, normal = 2, big = 15
    }

    func doGlowAnimation(withColor color: UIColor, withEffect effect: GlowEffect = .normal) {
        layer.masksToBounds = false
        layer.shadowColor = color.cgColor
        layer.shadowRadius = 0
        layer.shadowOpacity = 1
        layer.shadowOffset = .zero

        let glowAnimation = CABasicAnimation(keyPath: "shadowRadius")
        glowAnimation.fromValue = 0
        glowAnimation.toValue = effect.rawValue
        glowAnimation.beginTime = CACurrentMediaTime()+0.3
        glowAnimation.duration = CFTimeInterval(0.3)
        glowAnimation.fillMode = kCAFillModeRemoved
        glowAnimation.autoreverses = true
        glowAnimation.isRemovedOnCompletion = true
        layer.add(glowAnimation, forKey: "shadowGlowingAnimation")
    }
}

Как это использовать:

//TextField with border
textField.doGlowAnimation(withColor: UIColor.red, withEffect: .big)

//Label
label.doGlowAnimation(withColor: label.textColor, withEffect: .small)

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

Ответ 5

Вот мой ответ....

Использование категорий

/* ****FAQ?

 1.how to add glow effect on uibutton?
 [UIButton glowUIButton:playButton];

 2.how to remove effect on uibutton?
 [UIButton removeGlowUIButton:playButton];

 Ends*** */

#import <UIKit/UIKit.h>
@interface UIButton (BlinkEffect)
//blink effect category
+( void) glowUIButton:(UIButton *)inputButton;
//remove blink effect
+(void) removeGlowUIButton:(UIButton *)inputButton;
@end

#import "UIButton+BlinkEffect.h"

@implementation UIButton (BlinkEffect)

+(void) glowUIButton:(UIButton *)inputButton
{
    //add blink effect
    CALayer *viewLayer = inputButton.layer;
    viewLayer.shadowOffset = CGSizeMake(0,0);
    CGFloat radius = CGRectGetWidth(inputButton.bounds)/2.0;
    viewLayer.shadowColor = [[UIColor whiteColor] CGColor];
    viewLayer.shadowPath = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(-7,-5.5, 2.5 * (radius), 2.5 * radius) cornerRadius:radius].CGPath;
    viewLayer.shadowRadius = 5.0f;
    viewLayer.shadowOpacity = 1.0f;

    //Let animate it while we're at it.
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"shadowOpacity"];
    animation.duration =0.7;
    animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
    animation.fromValue = [NSNumber numberWithFloat:1.0];
    animation.toValue = [NSNumber numberWithFloat:0.0];
    animation.autoreverses = YES;
    animation.repeatCount = 1.0 / 0.0;
    [viewLayer addAnimation:animation forKey:@"shadowOpacity"];

}

+(void)removeGlowUIButton:(UIButton *)inputButton
{
    CALayer *viewLayer = inputButton.layer;
    viewLayer.shadowColor = [[UIColor clearColor] CGColor];
    [viewLayer removeAnimationForKey:@"shadowOpacity"];
}
@end