Objective-C的UIControl学习笔记

UIControl 简介

UIControl派生自UIView类,是作为响应用户交互而传递特定操作或意图的可视控件的基类。控件使用目标操作机制向应用程序报告用户交互。UISwitch开关、UIButton按钮、UISegmentedControl分段控件、UISlider滑块、UITextField文本字段控件、UIPageControl分页控件均派生自UIControl。

UIControl 常用属性
@property(nonatomic,readonly) UIControlState state;

属性描述控件的状态,指定为位掩码值。这个属性的值是UIControlState类型中常量的位掩码。控件可以同时处于多种状态。例如,它可以同时聚焦和高亮显示。还可以使用这个类的属性来获取各个状态的值。

@property(nonatomic,getter=isEnabled) BOOL enabled;

属性描述一个布尔值,指示控件是否处于启用状态。将此属性的值设置为YES以启用控件,或设置为NO以禁用控件。启用的控件能够响应用户交互,而禁用的控件会忽略触摸事件,并可能以不同的方式绘制自己。将此属性设置为NO会将UIControlStateDisabled标志添加到控件的状态位掩码;再次启用控制将删除该标志。对于新创建的控件,此属性的默认值为YES。

@property(nonatomic,getter=isSelected) BOOL selected; 

属性描述一个布尔值,指示控件是否处于选定状态。默认为“NO”,当用户选中控件时,UIControl类会将其selected属性设置为YES。子类有时使用这个属性来让控件选择自身,或者来表现不同的行为方式。

@property(nonatomic,getter=isHighlighted) BOOL highlighted; 

属性描述指示控件是否绘制高亮显示的布尔值,默认为“NO”。当此属性的值设置为YES时,控件将高亮显示,否则控件将不会绘制高亮显示。控件自动设置和清除此状态以响应适当的触摸事件,可以根据需要更改此属性的值,以编程方式应用或删除高亮显示。故事板文件中可以设置控件的初始选定状态。

@property(nonatomic) UIControlContentVerticalAlignment contentVerticalAlignment;

属性描述控件边界内内容的垂直对齐方式,默认为中心。

  • UIControlContentVerticalAlignment枚举值如下:
typedef NS_ENUM(NSInteger, UIControlContentVerticalAlignment) {
    UIControlContentVerticalAlignmentCenter        = 0,//控件内容垂直对齐中心
    UIControlContentVerticalAlignmentTop           = 1,//控件内容垂直对齐顶部
    UIControlContentVerticalAlignmentBottom     = 2,//控件内容垂直对齐底部
    UIControlContentVerticalAlignmentFill          = 3,//将内容垂直对齐以填充内容矩形,图像可能会被拉长。
};
@property(nonatomic) UIControlContentHorizontalAlignment contentHorizontalAlignment;

属性描述控件内容水平对齐方式,默认为中心。

  • UIControlContentHorizontalAlignment枚举值如下:
typedef NS_ENUM(NSInteger, UIControlContentHorizontalAlignment) {
    UIControlContentHorizontalAlignmentCenter = 0,//控制内容水平对齐中心
    UIControlContentHorizontalAlignmentLeft   = 1,//控制内容水平对齐左侧
    UIControlContentHorizontalAlignmentRight  = 2,//控制内容水平对齐右侧
    UIControlContentHorizontalAlignmentFill   = 3,//将内容水平对齐以填充内容矩形,图像可能会被拉伸
    UIControlContentHorizontalAlignmentLeading  API_AVAILABLE(ios(11.0), tvos(11.0)) = 4,//控制内容水平对齐头部
    UIControlContentHorizontalAlignmentTrailing API_AVAILABLE(ios(11.0), tvos(11.0)) = 5,//控制内容水平对齐尾部
};
@property(nonatomic, readonly) UIControlContentHorizontalAlignment effectiveContentHorizontalAlignment;

属性描述 :只读属性,控件当前有效的水平对齐方式。此属性始终包含值UIControlContentHorizontalAlignmentLeft或UIControlContentHorizontalAlignmentRight,即使在设置UIControlContentHorizontalAlignmentLeading或UIControlContentHorizontalAlignmentTrailing时也会返回UIControlContentHorizontalAlignmentLeft或UIControlContentHorizontalAlignmentRight。

@property(nonatomic,readonly,getter=isTracking) BOOL tracking;

属性描述 :一个布尔值,指示控件当前是否正在跟踪触摸事件。在跟踪触摸事件的过程中,控件将此属性的值设置为YES。当跟踪结束或由于任何原因被取消时,控件会将此属性设置为NO。

@property(nonatomic,readonly,getter=isTouchInside) BOOL touchInside;

属性描述 :一个布尔值,指示被跟踪的触摸事件当前是否在控件的边界内。在跟踪触摸事件的过程中,控件会更新此属性的值,以指示最近的触摸是否仍在控件的边界内。控件使用此信息来触发特定事件。例如进入或退出控件的触摸事件触发适当的拖动事件。如果最近的触摸事件的位置在控件的边界内,则为YES;如果不在,则为NO。

UIControl事件类型的枚举

UIControl类提供了一个标准的事件通知机制来进行事件注册和接收,可以在指定的控件在发生特定的事件时,通知代理类的一个方法。事件可以用逻辑OR合并在一起,因此可以再一次单独的addTarget调用中指定多个事件。例如注册一个事件:

[self.backControl addTarget:self action:@selector(backControlClick) forControlEvents:UIControlEventTouchUpInside];
  • UIControlEvents事件类型的枚举:
typedef NS_OPTIONS(NSUInteger, UIControlEvents) {
    // 控件被按下去的事件
    UIControlEventTouchDown                                         = 1 <<  0,   
    // 控件被重复点击的事件,点击次数超过一次
    UIControlEventTouchDownRepeat                                   = 1 <<  1,   
    // 在控件范围内按下并拖动的事件
    UIControlEventTouchDragInside                                   = 1 <<  2,   
    // 在控件范围内按下并在控件外面拖动的事件
    UIControlEventTouchDragOutside                                  = 1 <<  3,   
    // 从控件范围外拖动到控件范围内的事件
    UIControlEventTouchDragEnter                                    = 1 <<  4,   
    // 将手指从控件内拖动到控件边界外的事件
    UIControlEventTouchDragExit                                     = 1 <<  5,
     // 点击控件后在控件范围内释放触发事件
    UIControlEventTouchUpInside                                     = 1 <<  6,  
     // 点击控件后在控件范围外释放触发事件
    UIControlEventTouchUpOutside                                    = 1 <<  7,  
    // 触摸取消事件
    UIControlEventTouchCancel                                       = 1 <<  8,   
    // 当控件的值发生改变时触发的事件
    UIControlEventValueChanged                                      = 1 << 12,   
    // 由按钮触发的语义操作。
    UIControlEventPrimaryActionTriggered API_AVAILABLE(ios(9.0)) = 1 << 13,   
    // 文本控件开始编辑时触发的事件   
    UIControlEventEditingDidBegin                                   = 1 << 16,   
    //文本控件中的内容被改变时触发的事件
    UIControlEventEditingChanged                                    = 1 << 17,  
    // 文本控件结束编辑时触发的事件 
    UIControlEventEditingDidEnd                                     = 1 << 18,   
    // 文本控件内通过按下回车(或等价行为)结束编辑时触发的事件
    UIControlEventEditingDidEndOnExit                               = 1 << 19,   
    // 所有触摸事件
    UIControlEventAllTouchEvents                                    = 0x00000FFF, 
    // 所有关于文本编辑的事件 
    UIControlEventAllEditingEvents                                  = 0x000F0000,  
     // 为应用程序预留
    UIControlEventApplicationReserved                               = 0x0F000000, 
    // 为系统内部框架预留
    UIControlEventSystemReserved                                    = 0xF0000000,  
    //所有事件
    UIControlEventAllEvents                                         = 0xFFFFFFFF   
};

- (void)addTarget:(nullable id)target action:(SEL)action forControlEvents:(UIControlEvents)controlEvents;

函数描述将目标对象和操作方法与控件相关联。可以多次调用此方法来配置控件的多个目标和操作。使用目标参数和操作参数的相同值多次调用此方法也是安全的。控件维护其附加目标和操作的列表,以及每个控件支持的事件。

控件不会将对象保留在目标参数中。当目标对象连接到控件时,需要保持对目标对象的强引用。

为controlEvents参数指定值0不会阻止将事件发送到以前注册的目标和操作方法。要停止事件的传递,始终需要调用removeTarget:action:forControlEvents:方法。

参数:

target :目标对象,即调用其操作方法的对象。如果指定nil,UIKit将在响应程序链中搜索一个对象,该对象将响应指定的操作消息并将消息传递给该对象。

action :一个选择器,用于标识要调用的操作方法。此参数不能为nil。

controlEvents :一个位掩码,指定为其调用操作方法的控件特定事件。始终需要至少指定一个常量。

- (void)removeTarget:(nullable id)target action:(nullable SEL)action forControlEvents:(UIControlEvents)controlEvents;

函数描述停止将事件传递到指定的目标对象。使用此方法可以防止将控制事件传递到与控制关联的目标对象。如果在目标参数中指定了一个有效的对象,则此方法将停止向与该对象关联的所有操作方法传递指定的事件。如果为目标参数指定nil,则此方法将阻止将这些事件传递到所有目标对象的所有操作方法。

尽管在停止事件传递时不考虑操作参数,但无论如何都应该指定一个适当的值。如果指定的目标/操作组合不再具有与其关联的任何有效控制事件,则该控件将清理其相应的内部数据结构。

参数 :

target : 删除控件注册的目标对象。指定nil以删除所有目标对象的指定控制事。

action :一种选择器,用于标识已注册的操作方法。可以为此参数指定nil。

controlEvents :一个位掩码,用于指定要为指定的目标对象删除的控制事件。

\color{red}{利用UIControl点击阴影可以消失的阴影视图代码记录}

//  ShadowViewController.h

#import <UIKit/UIKit.h>

@interface ShadowViewController : UIViewControlle

@end
//  ShadowViewController.m

#import "ShadowViewController.h"
#import "ShadowView.h"

@interface ShadowViewController ()

@end

@implementation ShadowViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.layer.borderWidth= 1.5;
    [button setTitle:@"完成" forState:UIControlStateNormal];
    [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(buttonTestClicked:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
    button.translatesAutoresizingMaskIntoConstraints = NO;
    [NSLayoutConstraint activateConstraints:@[
        [button.centerYAnchor constraintEqualToAnchor:self.view.centerYAnchor constant:-45 / 2],
        [button.centerXAnchor constraintEqualToAnchor:self.view.centerXAnchor],
        [button.widthAnchor constraintEqualToConstant:75],
        [button.heightAnchor constraintEqualToConstant:45],
    ]];
}

- (void)buttonTestClicked:(UIButton *)sender {
    NSString *signLabel = @"<p>连续浇水7天,可得20鲸豆可得15.00元红包;</p><p>连续浇水14天,可得40鲸豆可得15.00元红包;</p><p>连续浇水21天,可得60鲸豆可得15.00元红包;</p><p>连续浇水28天,可得80鲸豆可得15.00元红包;";
    ShadowView *shadow = [[ShadowView alloc]initWithFrame:CGRectZero];
    shadow.signLabel = signLabel;
    [shadow showInView:self.view];
    [self setGradualChangeColorView:shadow];
}

///设置红包玩法背景渐变色
- (void)setGradualChangeColorView:(UIView *)view{
    //CAGradientLayer继承CALayer,可以设置渐变图层
    CAGradientLayer *grandientLayer = [[CAGradientLayer alloc] init];
    grandientLayer.frame = CGRectMake(0, 0, 300, 330);
    [view.layer addSublayer:grandientLayer];
    [view.layer insertSublayer:grandientLayer atIndex:0];
    //设置渐变的方向 左上(0,0)  右下(1,1)
    grandientLayer.startPoint = CGPointZero;
    grandientLayer.endPoint = CGPointMake(0.0, 1.0);
    //colors渐变的颜色数组 这个数组中只设置一个颜色是不显示的
    grandientLayer.colors = @[(id)[UIColor redColor].CGColor, (id)[UIColor orangeColor].CGColor];
    grandientLayer.type = kCAGradientLayerAxial;
}

@end
//  ShadowView.h

#import <UIKit/UIKit.h>

@interface ShadowView : UIView

@property (nonatomic, copy) NSString *signLabel;//红包玩法描述

- (void)showInView:(UIView *)view;
- (void)hideInView;

@end
//  ShadowView.m

#import "ShadowView.h"

@interface ShadowView()

@property (nonatomic, strong) UIControl * backControl;//视图控制层
@property (nonatomic, strong) UIScrollView *characterDescriptionView;//底部文字描述视图
@property (nonatomic, strong) UILabel *characterDescriptionLabel;//文字描述标签

@end

@implementation ShadowView

- (id)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        self.layer.cornerRadius = 10.0f;
        self.layer.masksToBounds = YES;
        self.hidden = YES;
        [self drawView];
    }
    return self;
}

- (void)drawView{
    ///视图控制层
    self.backControl = [[UIControl alloc]initWithFrame:CGRectMake(0, 0, UIScreen.mainScreen.bounds.size.width, UIScreen.mainScreen.bounds.size.height)];
    self.backControl.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.5];
    [self.backControl addTarget:self action:@selector(backControlClick) forControlEvents:UIControlEventTouchUpInside];
    self.backControl.alpha = 0;
    self.backgroundColor = [UIColor clearColor];
    ///底部文字描述视图
    self.characterDescriptionView = [[UIScrollView alloc]initWithFrame:CGRectZero];
    self.characterDescriptionView.backgroundColor = [UIColor colorWithWhite:1.0 alpha:0.3];
    self.characterDescriptionView.scrollEnabled = YES;
    self.characterDescriptionView.layer.cornerRadius = 10.0;
    self.characterDescriptionView.layer.masksToBounds = YES;
    [self addSubview:self.characterDescriptionView];
    self.characterDescriptionView.translatesAutoresizingMaskIntoConstraints = NO;
    [NSLayoutConstraint activateConstraints:@[
        [self.characterDescriptionView.topAnchor constraintEqualToAnchor:self.topAnchor constant:10],
        [self.characterDescriptionView.leftAnchor constraintEqualToAnchor:self.leftAnchor constant:15],
        [self.characterDescriptionView.rightAnchor constraintEqualToAnchor:self.rightAnchor constant:-15],
        [self.characterDescriptionView.heightAnchor constraintEqualToConstant:170],
    ]];
    ///文字描述标签
    self.characterDescriptionLabel = [[UILabel alloc]initWithFrame:CGRectZero];
    self.characterDescriptionLabel.font = [UIFont systemFontOfSize:16];
    self.characterDescriptionLabel.backgroundColor = [UIColor clearColor];
     self.characterDescriptionLabel.textColor = [UIColor whiteColor];
    self.characterDescriptionLabel.numberOfLines = 0;
    [self.characterDescriptionView addSubview:self.characterDescriptionLabel];
    self.characterDescriptionLabel.translatesAutoresizingMaskIntoConstraints = NO;
    [NSLayoutConstraint activateConstraints:@[
        [self.characterDescriptionLabel.topAnchor constraintEqualToAnchor:self.characterDescriptionView.topAnchor constant:10],
        [self.characterDescriptionLabel.bottomAnchor constraintEqualToAnchor:self.characterDescriptionView.bottomAnchor constant:-10],
        [self.characterDescriptionLabel.widthAnchor constraintEqualToConstant:280],
    ]];
}

///显示视图
- (void)showInView:(UIView *)view{
    if (self.isHidden) {
        self.hidden = NO;
        if (self.backControl.superview == nil) {
            [view addSubview:self.backControl];
        }
        [UIView animateWithDuration:0.2f animations:^{
            self.backControl.alpha = 1;
        }];
        [view addSubview:self];
        self.translatesAutoresizingMaskIntoConstraints = NO;
        [NSLayoutConstraint activateConstraints:@[
            [self.centerXAnchor constraintEqualToAnchor:view.centerXAnchor],
            [self.centerYAnchor constraintEqualToAnchor:view.centerYAnchor],
            [self.widthAnchor constraintEqualToConstant:300],
            [self.heightAnchor constraintEqualToConstant:190],
        ]];
    }
}

///隐藏视图
- (void)hideInView{
    if (!self.isHidden) {
        self.hidden = YES;
        [UIView animateWithDuration:0.2f animations:^{
            self.backControl.alpha=0;
        }completion:^(BOOL finished) {
            [self removeFromSuperview];
        }];
    }
}

///控制层点击事件
- (void)backControlClick{
    [self hideInView];
}

///设置红包玩法文本描述
- (void)setSignLabel:(NSString *)signLabel{
    self.characterDescriptionLabel.text = [self handleHtmlText:signLabel];
    self.characterDescriptionView.contentSize = CGSizeMake(0, [self.characterDescriptionLabel sizeThatFits:CGSizeMake(280, MAXFLOAT)].height);
}

///处理带<p></p>的字符串
- (NSMutableString *)handleHtmlText:(NSString *)htmlText{
    NSMutableString *mutableStr = [[NSMutableString alloc]init];
    if([htmlText containsString:@"</p>"]){
        NSArray *strArray = [htmlText componentsSeparatedByString:@"</p>"];
        for(int i = 0; i < strArray.count; i++){
            if([strArray[i] containsString:@"<p>"]){
                NSString *newStr = [strArray[i] stringByReplacingOccurrencesOfString:@"<p>" withString:@"•"];
                NSMutableString *mutableString = [[NSMutableString alloc]initWithString:newStr];
                [mutableString appendString:@"\r"];
                [mutableStr appendString:mutableString];
            }
        }
    }
    return mutableStr;
}

@end

效果:

Jietu20220803-111518-HD.gif
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 151,829评论 1 331
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 64,603评论 1 273
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 101,846评论 0 226
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 42,600评论 0 191
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 50,780评论 3 272
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 39,695评论 1 192
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,136评论 2 293
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 29,862评论 0 182
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 33,453评论 0 229
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 29,942评论 2 233
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,347评论 1 242
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 27,790评论 2 236
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,293评论 3 221
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 25,839评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,448评论 0 181
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 34,564评论 2 249
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 34,623评论 2 249

推荐阅读更多精彩内容

  • 本文主要讲解iOS触摸事件的一系列机制,涉及的问题大致包括: 触摸事件由触屏生成后如何传递到当前应用? 应用接收触...
    baihualinxin阅读 1,151评论 0 9
  • UIKit提供了一组控件:UISwitch开关、UIButton按钮、UISegmentedControl分段控件...
    脑子勺掉了吧你阅读 418评论 0 0
  • UIKit提供了一组控件:UISwitch开关、UIButtonbutton、UISegmentedCon...
    飞天小猪阅读 1,047评论 0 1
  • UIKit提供了一组控件:UISwitch开关、UIButton按钮、UISegmentedControl分段控件...
    朱亚宁95115阅读 6,499评论 1 7
  • UIKit提供了一组控件:UISwitch开关、UIButton按钮、UISegmentedControl分段控件...
    浪漫紫薇星阅读 1,266评论 0 0