iOS--寫一個可以自定義圖片的SwitchView

好久不寫UI、正好項目里遇到一個需要自定義圖片的SwitchView。
寫了寫封裝了一下、感覺挺有意思干脆貼出來好了、沒準對誰有用。

效果圖如下、有需要可以自取。


主要寫了以下的幾個功能

  • 可以設置X秒內不允許點擊。
  • 可以設置X秒后無新動作再的捕獲回調。
  • 自定義文字顏色、大小
  • 自定義背景色
  • 自定義圖片
.h文件如下
//
//  KTSwitchView.h
//  BaiSongInternational
//
//  Created by 劉嵩野 on 2018/4/3.
//  Copyright ? 2018年 maqihan. All rights reserved.
//

#import <UIKit/UIKit.h>
@class KTSwitchView;

typedef NS_OPTIONS(NSUInteger, KTSwitchViewStyle) {
    //選中狀態
    KTSwitchViewStyle_Selected = 1 << 0,
    //普通狀態
    KTSwitchViewStyle_Default = 1 << 1,
};


@protocol KTSwitchViewDelegate<NSObject>
/**
 * selected屬性改變的時候調用
 */
- (void)KTSwichViewDidChange:(KTSwitchView *)swichView;
/**
 * selected一定時間后沒有再改變時調用 默認0s、也就是不走這個回調
 */
- (void)KTSwichViewDidDelayChange:(KTSwitchView *)swichView;

@end
@interface KTSwitchView : UIView

@property (nonatomic, weak) id <KTSwitchViewDelegate> delegate;
/* 延遲多久可以再次點擊 */
@property (nonatomic, assign) NSTimeInterval eventInterval;
/* 延遲多久回調 BSSwichViewDidDelayChange 默認0s*/
@property (nonatomic, assign) NSTimeInterval delayTime;
@property (nonatomic) UIFont * font;
@property (nonatomic) BOOL selected;


/**
 *  可以KTSwitchViewStyle_Default|KTSwitchViewStyle_Selected同時設定兩種狀態
 */
- (void)setContentText:(NSString *)contentText style:(KTSwitchViewStyle)style;
- (void)setTextColor:(UIColor *)textColor style:(KTSwitchViewStyle)style;
- (void)setImage:(UIImage *)img style:(KTSwitchViewStyle)style;
- (void)setImageBgColor:(UIColor *)color style:(KTSwitchViewStyle)style;
- (void)setBgcolor:(UIColor *)bgcolor style:(KTSwitchViewStyle)style;

@end

需要注意的是

  • 布局使用的是Masonry、需要項目支持。
  • 延遲回調用的是NSOperation隊列、每次點擊廢棄隊列中的舊操作。
    其實也可以(或者說從場景上更適合)用定時器、但是個人情感上不太喜歡不斷的開關某個定時器。

有需要可以自取《Github》

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容