iOS-Runtime使用-给任何继承UIView的控件添加Tip提示

该Demo只是提供一种思路、如果有更好的idea、请不吝赐教

效果图


WechatIMG44.jpeg

代码如下:

#import 

@interface YYTipLabel : UILabel
@end

@interface UIView (YYTip)
- (void)showTip:(NSString *)tip;
- (void)hiddenTip;
@end
#import "YYTipLabel.h"
#import 

@implementation YYTipLabel
@end


#pragma mark - 动态的给UIView添加属性
static char TipLabelKey;
@implementation UIView (YYTip)
- (void)setTipLabel:(YYTipLabel *)tipLabel {
    objc_setAssociatedObject(self, &TipLabelKey,
                             tipLabel,
                             OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (YYTipLabel *)tipLabel {
    return objc_getAssociatedObject(self, &TipLabelKey);
}
- (void)showTip:(NSString *)tip {
    if (!self.tipLabel) {
        self.tipLabel = [[YYTipLabel alloc]init];
        [self addSubview:self.tipLabel];
        self.tipLabel.text = tip;
        self.tipLabel.frame = CGRectMake(0, -20, 150, 20);
        self.tipLabel.hidden = NO;
        [self.tipLabel setFont:[UIFont systemFontOfSize:10]];
        self.tipLabel.numberOfLines = 0;
        self.tipLabel.textColor = [UIColor redColor];
        self.tipLabel.backgroundColor = [UIColor yellowColor];
        self.tipLabel.textAlignment = NSTextAlignmentLeft;
    }
}
- (void)hiddenTip {
    if (self.tipLabel) {
        self.tipLabel.hidden = YES;
        [self.tipLabel removeFromSuperview];
        self.tipLabel = nil;
    }
}
@end

使用方法:

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(10, 100, 150, 50)];
    label.text = @"我是label";
    label.backgroundColor = [UIColor redColor];
    label.textColor = [UIColor whiteColor];
    label.numberOfLines = 0;
    [self.view addSubview:label];
    [label showTip:@"我是一个label"];
    
    //[label hiddenTip];//隐藏Tip

    UITextField *textField = [[UITextField alloc]init];
    [self.view addSubview:textField];
    textField.text = @"我是textField";
    textField.frame = CGRectMake(10, 200, 150, 50);
    textField.backgroundColor = [UIColor redColor];
    textField.textColor = [UIColor whiteColor];
    [textField showTip:@"我是textField"];
}

可直接复制到自己的项目中使用,也可通过Demo下载查看

兄弟篇:RunTime使用-给空白页添加占位图

你可能感兴趣的:(iOS-Runtime使用-给任何继承UIView的控件添加Tip提示)