iOS开发swift自定义AlertController弹出带有输入框后AertView

来源:互联网 发布:手机浏览器知乎 编辑:程序博客网 时间:2024/05/21 07:42

1. 使用方式(swift):

        let joopicAlert = JoopicAlertController(title: "设置昵称", image: UIImage(named: "grid_blue"), message: "设置后,其他人将看到你的昵称",textholder:"在此输入昵称")        joopicAlert.addAction(SHBAction(title: "取消", action: nil))        joopicAlert.addAction(SHBAction(title: "保存", action: {           self.saveNickName(joopicAlert.content)        }))        joopicAlert.show()


2. 源码:JoopicAlertController.h

#import <UIKit/UIKit.h>@interface SHBAction : NSObject@property (nonatomic, readonly, copy) NSString            *title;@property (nonatomic, readonly, copy) dispatch_block_t    action;+ (SHBAction *)actionWithTitle:(NSString *)title action:(dispatch_block_t)action;- (id)initWithTitle:(NSString *)title action:(dispatch_block_t)action;@end@interface JoopicAlertController : UIViewController@property (nonatomic, strong, readonly) NSString *content;- (id)initWithTitle:(NSString *)title image:(UIImage *)image message:(NSString *)message textholder:(NSString *)textholder;- (void)addAction:(SHBAction *)action;- (void)show;@end

JoopicAlertController.m

#import "JoopicAlertController.h"#import "HexColors.h"@implementation SHBAction- (id)initWithTitle:(NSString *)title action:(dispatch_block_t)action {    self = [super init];    if (self) {        _title = title;        _action = action;    }    return self;}+ (SHBAction *)actionWithTitle:(NSString *)title action:(dispatch_block_t)action {    SHBAction *ac = [[SHBAction alloc] initWithTitle:title action:action];    return ac;}@end@interface JoopicAlertController ()@endCGFloat backViewH = 197.5;@implementation JoopicAlertController {    NSString            *_title;    UIImage             *_image;    NSString            *_message;    NSString            *_textholder;        UIView              *_backView;        UILabel             *_titleLbl;    UIImageView         *_photo;    UILabel             *_messageLbl;    UITextField         *_textField;        UIButton            *_cancel;    UIButton            *_send;        UIView              *_hLine;    UIView              *_vLine;        CGFloat             _backBottom;    NSLayoutConstraint  *_bottom;        NSMutableArray      *_actions;}- (id)initWithTitle:(NSString *)title image:(UIImage *)image message:(NSString *)message textholder:(NSString *)textholder{    self = [super init];    if (self) {        _title = title;        _image = image;        _message = message;        _textholder = textholder;        _actions = [[NSMutableArray alloc] initWithCapacity:0];    }    return self;}- (void)viewDidLoad {    [super viewDidLoad];    // Do any additional setup after loading the view.    self.view.backgroundColor = [UIColor colorWithWhite:0.5 alpha:0.5];        _backBottom = -(CGRectGetHeight(self.view.frame) - backViewH) / 2.;        _backView = [[UIView alloc] initWithFrame:CGRectZero];    _backView.translatesAutoresizingMaskIntoConstraints = false;    _backView.backgroundColor = [UIColor whiteColor];    _backView.layer.cornerRadius = 10;    _backView.layer.masksToBounds = true;    [self.view addSubview:_backView];        _titleLbl = [[UILabel alloc] initWithFrame:CGRectZero];    _titleLbl.textAlignment = NSTextAlignmentCenter;    _titleLbl.translatesAutoresizingMaskIntoConstraints = false;        _titleLbl.textColor = [UIColor hx_colorWithHexString:@"000000"];    _titleLbl.font = [UIFont systemFontOfSize:18];    _titleLbl.text = _title;    [_backView addSubview:_titleLbl];    //    _photo = [[UIImageView alloc] initWithFrame:CGRectZero];//    _photo.translatesAutoresizingMaskIntoConstraints = false;//    _photo.layer.cornerRadius = 2;//    _photo.layer.masksToBounds = true;//    _photo.image = _image;//    [_backView addSubview:_photo];        _messageLbl = [[UILabel alloc] initWithFrame:CGRectZero];    _messageLbl.textAlignment = NSTextAlignmentCenter;    _messageLbl.translatesAutoresizingMaskIntoConstraints = false;    _messageLbl.textColor = [UIColor hx_colorWithHexString:@"333333"];    _messageLbl.font = [UIFont systemFontOfSize:12];    _messageLbl.text = _message;    [_backView addSubview:_messageLbl];        _textField = [[UITextField alloc] initWithFrame:CGRectZero];    _textField.translatesAutoresizingMaskIntoConstraints = false;    _textField.layer.borderColor = [UIColor hx_colorWithHexString:@"e2e1e1"].CGColor;    _textField.layer.borderWidth = 1 / [UIScreen mainScreen].scale;    _textField.layer.cornerRadius = 2;    _textField.leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 30)];    _textField.leftViewMode = UITextFieldViewModeAlways;    _textField.backgroundColor = [UIColor whiteColor];    _textField.placeholder = _textholder;    [_backView addSubview:_textField];            UIColor *lineColor = [UIColor hx_colorWithHexString:@"e3e1e4"];        _hLine = [[UIView alloc] initWithFrame:CGRectZero];    _hLine.translatesAutoresizingMaskIntoConstraints = false;    _hLine.backgroundColor = lineColor;    [_backView addSubview:_hLine];        _vLine = [[UIView alloc] initWithFrame:CGRectZero];    _vLine.translatesAutoresizingMaskIntoConstraints = false;    _vLine.backgroundColor = lineColor;    [_backView addSubview:_vLine];        _cancel = [UIButton buttonWithType:UIButtonTypeSystem];    _cancel.translatesAutoresizingMaskIntoConstraints = false;        NSString *cancel = [(SHBAction *)_actions[0] title];    [_cancel setTitle:cancel forState:UIControlStateNormal];    [_cancel setTitleColor:[UIColor hx_colorWithHexString:@"999999"] forState:UIControlStateNormal];    _cancel.titleLabel.font = [UIFont systemFontOfSize:15];    [_cancel addTarget:self action:@selector(shbClickedBtn:) forControlEvents:UIControlEventTouchUpInside];    _cancel.tag = 100;    [_backView addSubview:_cancel];        _send = [UIButton buttonWithType:UIButtonTypeSystem];    _send.translatesAutoresizingMaskIntoConstraints = false;    NSString *send = [(SHBAction *)_actions[1] title];    [_send setTitle:send forState:UIControlStateNormal];    [_send setTitleColor:[UIColor hx_colorWithHexString:@"797ca1"] forState:UIControlStateNormal];    _send.titleLabel.font = [UIFont systemFontOfSize:15];    [_send addTarget:self action:@selector(shbClickedBtn:) forControlEvents:UIControlEventTouchUpInside];    _send.tag = 200;    [_backView addSubview:_send];            NSDictionary *views = NSDictionaryOfVariableBindings(_backView, _titleLbl, _messageLbl, _textField, _hLine, _vLine, _cancel, _send);    NSDictionary *met = @{@"one" : @(1 / [UIScreen mainScreen].scale)};        [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"|-30-[_backView]-30-|" options:0 metrics:nil views:views]];    _bottom = [NSLayoutConstraint constraintWithItem:_backView attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeBottom multiplier:1 constant:_backBottom];    [self.view addConstraint:_bottom];        [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-12-[_titleLbl]-12-[_messageLbl]-12-[_textField(38)]-12-[_hLine(one)][_cancel(44)]|" options:0 metrics:met views:views]];    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[_hLine][_send]|" options:0 metrics:nil views:views]];    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[_hLine][_vLine]|" options:0 metrics:nil views:views]];        [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"|-17-[_titleLbl]-17-|" options:0 metrics:nil views:views]];    //[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"|-17-[_photo(50)]-10-[_messageLbl]-17-|" options:0 metrics:nil views:views]];    //[self.view addConstraint:[NSLayoutConstraint constraintWithItem:_messageLbl attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:_photo attribute:NSLayoutAttributeCenterY multiplier:1 constant:0]];    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"|-17-[_messageLbl]-17-|" options:0 metrics:nil views:views]];        [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"|-17-[_textField]-17-|" options:0 metrics:nil views:views]];        [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"|[_hLine]|" options:0 metrics:nil views:views]];    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"|[_cancel][_vLine(one)][_send(_cancel)]|" options:0 metrics:met views:views]];    self.view.layer.shouldRasterize = true;    self.view.layer.rasterizationScale = [UIScreen mainScreen].scale;        [self registerKeyBoard];}- (void)keyBoardShow:(NSNotification *)info {        NSValue *keyBoardRect = [[info userInfo] valueForKey:UIKeyboardFrameEndUserInfoKey];    CGRect keyRect = [keyBoardRect CGRectValue];        if (_backBottom > -keyRect.size.height) {        _bottom.constant = -30 - keyRect.size.height;    }        [UIView animateWithDuration:0.25 animations:^{        [self.view layoutIfNeeded];    }];}- (void)keyBoardHidden:(NSNotification *)info {    _bottom.constant = _backBottom;    [UIView animateWithDuration:0.25 animations:^{        [self.view layoutIfNeeded];    }];}- (void)shbClickedBtn:(UIButton *)btn {    _content = _textField.text;    if (btn.tag == 100) {        SHBAction *action = _actions[0];        if (action.action) {            action.action();        }    } else {        SHBAction *action = _actions[1];        if (action.action) {            action.action();        }    }    [self dismiss];}- (void)addAction:(SHBAction *)action {    [_actions addObject:action];}- (void)show {    UIViewController *result = [self currentController];    [result addChildViewController:self];    [result.view addSubview:self.view];    [_textField becomeFirstResponder];}- (void)dismiss {    __weak typeof(self) SHB = self;    [UIView animateWithDuration:0.1 animations:^{        [SHB.view removeFromSuperview];        [SHB removeFromParentViewController];    } completion:^(BOOL finished) {        [SHB removeKeyBoard];    }];}- (UIViewController *)currentController {    UIViewController *result = nil;    UIWindow *window = [[UIApplication sharedApplication] keyWindow];        if (window.windowLevel != UIWindowLevelNormal) {        NSArray *windows = [[UIApplication sharedApplication] windows];                for (UIWindow *temWin in windows) {            if (temWin.windowLevel == UIWindowLevelNormal) {                window = temWin;                break;            }        }    }        UIView *frontView = [[window subviews] objectAtIndex:0];    id nestResponder = [frontView nextResponder];    if ([nestResponder isKindOfClass:[UIViewController class]]) {        result = nestResponder;    } else {        result = window.rootViewController;    }    return result;}#pragma mark - Keyboard- (void)registerKeyBoard {    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardShow:) name:UIKeyboardDidShowNotification object:nil];    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardHidden:) name:UIKeyboardDidHideNotification object:nil];}- (void)removeKeyBoard {    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardDidShowNotification object:nil];    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardDidHideNotification object:nil];}- (void)didReceiveMemoryWarning {    [super didReceiveMemoryWarning];    // Dispose of any resources that can be recreated.}- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {    [_textField resignFirstResponder];}@end

HexColors.h

////  HexColor.h////  Created by Marius Landwehr on 02.12.12.//  The MIT License (MIT)//  Copyright (c) 2013 Marius Landwehr marius.landwehr@gmail.com////  Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:////  The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.////  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.//#import "TargetConditionals.h"#if TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR  #import <UIKit/UIKit.h>  #define HXColor UIColor#else  #import <Cocoa/Cocoa.h>  #define HXColor NSColor#endif@interface HXColor (HexColorAddition)+ (HXColor *)hx_colorWithHexString:(NSString *)hexString;+ (HXColor *)hx_colorWithHexString:(NSString *)hexString alpha:(CGFloat)alpha;+ (HXColor *)hx_colorWith8BitRed:(NSInteger)red green:(NSInteger)green blue:(NSInteger)blue;+ (HXColor *)hx_colorWith8BitRed:(NSInteger)red green:(NSInteger)green blue:(NSInteger)blue alpha:(CGFloat)alpha;@end

HexColors.m

////  HexColor.m////  Created by Marius Landwehr on 02.12.12.//  The MIT License (MIT)//  Copyright (c) 2013 Marius Landwehr marius.landwehr@gmail.com////  Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:////  The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.////  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.//#import "HexColors.h"@implementation HXColor (HexColorAddition)+ (HXColor *)hx_colorWithHexString:(NSString *)hexString{    // Check for hash and add the missing hash    if('#' != [hexString characterAtIndex:0])    {        hexString = [NSString stringWithFormat:@"#%@", hexString];    }    CGFloat alpha = 1.0;    if (5 == hexString.length || 9 == hexString.length) {        NSString * alphaHex = [hexString substringWithRange:NSMakeRange(1, 9 == hexString.length ? 2 : 1)];        if (1 == alphaHex.length) alphaHex = [NSString stringWithFormat:@"%@%@", alphaHex, alphaHex];        hexString = [NSString stringWithFormat:@"#%@", [hexString substringFromIndex:9 == hexString.length ? 3 : 2]];        unsigned alpha_u = [[self class] hx_hexValueToUnsigned:alphaHex];        alpha = ((CGFloat) alpha_u) / 255.0;    }    return [[self class] hx_colorWithHexString:hexString alpha:alpha];}+ (HXColor *)hx_colorWithHexString:(NSString *)hexString alpha:(CGFloat)alpha{    if (hexString.length == 0) {        return nil;    }        // Check for hash and add the missing hash    if('#' != [hexString characterAtIndex:0])    {        hexString = [NSString stringWithFormat:@"#%@", hexString];    }        // check for string length    if (7 != hexString.length && 4 != hexString.length) {        NSString *defaultHex    = [NSString stringWithFormat:@"0xff"];        unsigned defaultInt = [[self class] hx_hexValueToUnsigned:defaultHex];                HXColor *color = [HXColor hx_colorWith8BitRed:defaultInt green:defaultInt blue:defaultInt alpha:1.0];        return color;    }        // check for 3 character HexStrings    hexString = [[self class] hx_hexStringTransformFromThreeCharacters:hexString];        NSString *redHex    = [NSString stringWithFormat:@"0x%@", [hexString substringWithRange:NSMakeRange(1, 2)]];    unsigned redInt = [[self class] hx_hexValueToUnsigned:redHex];        NSString *greenHex  = [NSString stringWithFormat:@"0x%@", [hexString substringWithRange:NSMakeRange(3, 2)]];    unsigned greenInt = [[self class] hx_hexValueToUnsigned:greenHex];        NSString *blueHex   = [NSString stringWithFormat:@"0x%@", [hexString substringWithRange:NSMakeRange(5, 2)]];    unsigned blueInt = [[self class] hx_hexValueToUnsigned:blueHex];        HXColor *color = [HXColor hx_colorWith8BitRed:redInt green:greenInt blue:blueInt alpha:alpha];        return color;}+ (HXColor *)hx_colorWith8BitRed:(NSInteger)red green:(NSInteger)green blue:(NSInteger)blue{    return [[self class] hx_colorWith8BitRed:red green:green blue:blue alpha:1.0];}+ (HXColor *)hx_colorWith8BitRed:(NSInteger)red green:(NSInteger)green blue:(NSInteger)blue alpha:(CGFloat)alpha{    HXColor *color = nil;#if (TARGET_IPHONE_SIMULATOR || TARGET_OS_IPHONE)    color = [HXColor colorWithRed:(float)red/255 green:(float)green/255 blue:(float)blue/255 alpha:alpha];#else    color = [HXColor colorWithCalibratedRed:(float)red/255 green:(float)green/255 blue:(float)blue/255 alpha:alpha];#endif        return color;}+ (NSString *)hx_hexStringTransformFromThreeCharacters:(NSString *)hexString{    if(hexString.length == 4)    {        hexString = [NSString stringWithFormat:@"#%1$c%1$c%2$c%2$c%3$c%3$c",                     [hexString characterAtIndex:1],                     [hexString characterAtIndex:2],                     [hexString characterAtIndex:3]];            }        return hexString;}+ (unsigned)hx_hexValueToUnsigned:(NSString *)hexValue{    unsigned value = 0;        NSScanner *hexValueScanner = [NSScanner scannerWithString:hexValue];    [hexValueScanner scanHexInt:&value];        return value;}@end


原始文档:http://code.cocoachina.com/view/128371

0 0
原创粉丝点击