iOS custom Alertview, inherited from UIView, can add child view, title picture + text

Source: Internet
Author: User

Custom Alertview, inherited from UIView, can add a child view in the message area: Addcustomersubview

title can have pictures + text composition,supports only two button actions


-Call the Alertview Show method on the controller that requires alert

Customalertview *alertview = [[Customalertview alloc] initwithtitle:@ "hint" message:@                                                        "Dylan_lwb_"                                                       delegate: Self                                              cancelbuttontitle:@ "OK"                                              Otherbuttontitles:nil];    [Alertview show];    [Alertview release];



-Create a Customalertview category in the project and copy all the code below

<span style= "font-family:arial, Helvetica, Sans-serif;" > #if defined (__apple_cc__) && (__apple_cc__ >= 5549) </span>
#define Ns_requires_nil_termination __attribute__ (Sentinel (0,1)) #else # define Ns_requires_nil_termination __ attribute__ (Sentinel) #endif # define Screen_width [[UIScreen mainscreen] Bounds].size.width#define screen_height [[U Iscreen Mainscreen] Bounds].size.height#define Rgba_color (R, G, B, a) [Uicolor colorwithred:r/255.0f green:g/255.0f Blue : b/255.0f alpha:a] #define KBCALERTVIEWPRESENTNOTIFY @ "kbcalertviewpresentnotify"//alertview present Notify#import & Lt foundation/foundation.h> #import <UIKit/UIKit.h> @class customalertview @protocol mbalertviewdelegate < Nsobject> @optional//-Proxy Method-(void) Alertview: (Customalertview *) Alertview Clickedbuttonatindex: (Nsinteger) buttonindex;-(void) alertviewclosed: (Customalertview *) alertview;-(void) Willpresentcustomalertview: (UIView *) alertview;//-Hide Utility Class popup keyboard-(void) Hidecurrentkeyboard; @end @interface Customalertview:uiview {} @property (nonatomic, Assign) ID <MBAlertViewDelegate> delegate; @property (nonatomic, assign) BOOL          ISNEEDCLOSEBTN; -left upper corner with fork Button @property (nonatomic, retain) nsstring *title; @property (nonatomic, retain) nsstring *message; @pr Operty (nonatomic, retain) UIView *backview; @property (nonatomic, retain) UIView *titlebackgroundview; @pro Perty (nonatomic, retain) UILabel *titlelabel; @property (nonatomic, retain) Uiimageview *titleicon; @property (No Natomic, retain) Nsmutablearray *customerviewstobeadd;-(ID) initwithtitle: (nsstring*) title message: (nsstring*) Message delegate: (ID) Delegate Cancelbuttontitle: (nsstring*) cancelbuttontitle otherbuttontitles: (nsstring*) Otherbuttontitles, ... ns_requires_nil_termination;-(void) Inittitle: (nsstring*) title message: (nsstring*) message delegate: (ID) del Cancelbuttontitle: (nsstring*) cancelbtntitle otherbuttontitles: (nsstring*) Otherbtntitles, ... ns_requires_nil_termination;-(void) show;//-Add custom control in Alertview-(void) Addcustomersubview: (UIView *) view;+ (void) Exchangeout: (UIView *) Changeoutview dur: (CftimeintervaL) dur;+ (Customalertview *) Defaultalert; @end 


#import "CustomAlertView.h" @interface Customalertview () {BOOL _isshow;} @property (nonatomic, retain) nsstring *cancelbuttontitle; @property (nonatomic, retain) Nsmutablearray *otherbuttont itles; @end @implementation customalertviewstatic const CGFloat mwidth = 290;static Const CGFloat mheight = 180;static cons T cgfloat mmaxheight = 250;static Const CGFloat mbtnheight = 30;static Const CGFloat mbtnwidth = 110;static cons T cgfloat mheaderheight = 40;+ (Customalertview *) defaultalert{static Customalertview *sharecenter = Nil;if (!shareCen ter) {sharecenter = [[Customalertview alloc] init];} return sharecenter;} -(Nsmutablearray *) customerviewstobeadd{if (_customerviewstobeadd = = nil) {_customerviewstobeadd = [[NSMut    Ablearray alloc] init]; } return _customerviewstobeadd;}    -(ID) init{self = [Super Initwithframe:cgrectmake (0, 0, screen_width, Screen_height + 20)];    if (self) {_isshow = NO; } return self;} -(ID) Initwithtitle: (NSstring*) title message: (nsstring*) message delegate: (ID) del cancelbuttontitle: (nsstring*) Cancelbtntitle Otherbuttontitles: (nsstring*) Otherbtntitles, ...    {self = [super Initwithframe:cgrectmake (0, 0, screen_width, Screen_height + 20)];        if (self) {self.delegate = del;        Self.cancelbuttontitle = Cancelbtntitle;        SELF.ISNEEDCLOSEBTN = NO;            if (!_otherbuttontitles) {va_list argList;                if (otherbtntitles) {self.otherbuttontitles = [Nsmutablearray array];            [Self.otherbuttontitles Addobject:otherbtntitles];            } va_start (ArgList, otherbtntitles);            ID arg;            while (arg = Va_arg (argList, id)) {[Self.otherbuttontitles addobject:arg];        }} self.title = title;            self.message = message; } return self;} -(void) Inittitle: (nsstring*) title message: (nsstring*) message delegate: (ID) del CancelbuttontiTle: (nsstring*) cancelbtntitle otherbuttontitles: (nsstring*) Otherbtntitles, ...        {if (self) {self.delegate = del;        Self.cancelbuttontitle = Cancelbtntitle;                SELF.ISNEEDCLOSEBTN = NO;            if (!_otherbuttontitles) {va_list argList;                if (otherbtntitles) {self.otherbuttontitles = [Nsmutablearray array];            [Self.otherbuttontitles Addobject:otherbtntitles];            } va_start (ArgList, otherbtntitles);            ID arg;            while (arg = Va_arg (argList, id)) {[Self.otherbuttontitles addobject:arg];        }} self.title = title;    self.message = message;        }}-(void) layoutsubviews{[Super Layoutsubviews];    For (UIView *view in [self subviews]) {[View Removefromsuperview];    } UIView *bgview = [[UIView alloc] initWithFrame:self.frame];   [Bgview Setbackgroundcolor:[uicolor Blackcolor]; [Bgview setalpha:0.4];    [Self addsubview:bgview];        [Bgview release];        if (!_backview) {_backview = [[UIView alloc] Initwithframe:cgrectmake (0, 0, Mwidth, mheight)];        _backview.opaque = NO;        _backview.backgroundcolor = [Uicolor Whitecolor];        _backview.layer.shadowoffset = Cgsizemake (1, 1);        _backview.layer.shadowradius = 2.0; _backview.layer.shadowcolor = [Uicolor Graycolor].        Cgcolor;        _backview.layer.shadowopacity = 0.8;    [_backview.layer Setmaskstobounds:no]; }//-Set Head display area//-set title background UIView *titleview = [[UIView alloc] Initwithframe:cgrectmake (0, 0, Mwidth, mheaderhe    ight)];    Titleview.backgroundcolor = Rgba_color (36, 193, 64, 1);    Cgsize titlesize = Cgsizezero; if (self.title && [self.title length] > 0) {titlesize = [self.title sizewithfont:[uifont Fontwithnam    e:@ "Helvetica-bold" size:18.0f]; } if (Titlesize.width > 0) {//-title picture CGFloat startX = (titleview.frame.size.width-40-titlesize.width)/2;        Uiimageview *titleimage = [[Uiimageview alloc] initwithimage:[uiimage imagenamed:@ "Xxxxx.png"];        Titleimage.frame = CGRectMake (StartX, (titleview.frame.size.height-30)/2, 30, 30);        Self.titleicon = Titleimage;        [Titleview Addsubview:titleimage];        [Titleimage release];                StartX + = 40; -title UILabel *titlelabel = [[UILabel alloc] Initwithframe:cgrectmake (StartX, (titleview.frame.size.height-20)                /2, Titlesize.width, 20)]; -The title is too long to handle if (TitleLabel.frame.size.width >) {titlelabel.frame = CGRectMake (tit            LEVIEW.FRAME.SIZE.HEIGHT-20)/2, mWidth-60, 20);        Titleimage.frame = CGRectMake (5, (titleview.frame.size.height-30)/2, 30, 30);        } titlelabel.text = Self.title;        Titlelabel.font = [Uifont fontwithname:@ "Helvetica-bold" size:18.0f]; Titlelabel.textcolor = [UIColor Whitecolor];        Titlelabel.backgroundcolor = [Uicolor Clearcolor];        Self.titlelabel = Titlelabel;        [Titleview Addsubview:titlelabel];    [Titlelabel release]; }else {//-title picture Uiimageview *titleimage = [[Uiimageview alloc] Initwithimage:[uiimage imagenamed:@ "xxxx        X.png "];        Titleimage.frame = CGRectMake ((titleview.frame.size.width-30)/2, (titleview.frame.size.height-30)/2, 30, 30);        [Titleview Addsubview:titleimage];    [Titleimage release]; } if (self.isneedclosebtn) {UIButton *btn = [[UIButton alloc]initwithframe:cgrectmake (Mwidth-mheaderheig        HT, 0, Mheaderheight, mheaderheight)];        Btn.backgroundcolor = [Uicolor Clearcolor];        [Btn setimage:[uiimage imagenamed:@ "Btn_close_alertview.png"] forstate:uicontrolstatenormal];        [Btn addtarget:self Action: @selector (closebtnclicked:) forcontrolevents:uicontroleventtouchupinside];        [Titleview ADDSUBVIEW:BTN];   [BTN release]; } [_backview Addsubview:titleview];    Self.titlebackgroundview = Titleview;        [Titleview release]; -Set message display area Uiscrollview *msgview = [[Uiscrollview alloc] Initwithframe:cgrectmake (0, Mheaderheight, Mwidth, (mHeight    -mheaderheight * 2)];        -Set Background color Msgview.backgroundcolor = [Uicolor Whitecolor];    -Content Cgsize messagesize = Cgsizezero; if (self.message && [Self.message length]>0) {messagesize = [self.message sizewithfont:[uifont syste                MFONTOFSIZE:16.0F] Constrainedtosize:cgsizemake (mWidth-20, maxfloat) linebreakmode:nslinebreakbywordwrapping];            if (Messagesize.width > 0) {UILabel *msglabel = [[UILabel alloc] init];            Msglabel.font = [Uifont systemfontofsize:16.0f];            Msglabel.text = Self.message;            Msglabel.numberoflines = 0;            Msglabel.textalignment = Nstextalignmentcenter;            Msglabel.backgroundcolor = [Uicolor Clearcolor]; MsgLabel.frame = CGRectMake (((Mheight-mheaderheight * 2)-messagesize.height)/2, mWidth-20, Messagesize.height + 5); if (Messagesize.height > Mmaxheight) {msgview.frame = CGRectMake (msgView.frame.or                Igin.x, MSGVIEW.FRAME.ORIGIN.Y, MsgView.frame.size.width, Mmaxheight + 25);                _backview.frame = CGRectMake (0, 0, mwidth, Mheaderheight * 2 + msgView.frame.size.height);                Msglabel.textalignment = Nstextalignmentleft;                Msglabel.frame = CGRectMake (ten, ten, mWidth-20, messagesize.height);            Msgview.contentsize = Cgsizemake (msgView.frame.size.width, msgLabel.frame.size.height + 20); } else if (Messagesize.height > (mheight-mheaderheight * 2)-ten) {Msgview.frame                = CGRectMake (msgview.frame.origin.x, MSGVIEW.FRAME.ORIGIN.Y, MsgView.frame.size.width, Messagesize.height + 25); _backview.frame = CGRectMake (0, 0, mwidth, Mheaderheight *2 + msgView.frame.size.height);            Msglabel.frame = CGRectMake (ten, ten, mWidth-20, Messagesize.height + 5);            } [Msgview Addsubview:msglabel];            [Msglabel release];        [_backview Addsubview:msgview];            }}else{if (Self.customerviewstobeadd && [self.customerviewstobeadd Count] > 0) {            CGFloat starty = 0;                For (UIView *subview in Self.customerviewstobeadd) {CGRect rect = subview.frame;                RECT.ORIGIN.Y = Starty;                Subview.frame = rect;                [Msgview Addsubview:subview];            Starty + = Rect.size.height;        } msgview.frame = CGRectMake (0, Mheaderheight, Mwidth, starty);        } [_backview Addsubview:msgview];    _backview.frame = CGRectMake (0, 0, mwidth, MsgView.frame.size.height + mheaderheight * 2 +20);      } [Msgview release]; -Set button display area if (_otherbuttontitles! = Nil | |_cancelbuttontitle = nil) {UIView *btnview = [[UIView alloc] Initwithframe:cgrectmake (0, _backview.frame.size.                Height-mheaderheight, Mwidth, Mheaderheight)];  -If only one button is displayed, you need to calculate the display size of the button if (_otherbuttontitles = = Nil | | _cancelbuttontitle = nil) {UIButton *BTN = [[UIButton alloc]initwithframe:cgrectmake ((_backview.frame.size.width-mbtnwidth)/2, 0, Mbtnwidth, mBtnHeight)            ];            Btn.backgroundcolor = Rgba_color (36, 193, 64, 1);            Btn.titleLabel.font = [Uifont fontwithname:@ "Helvetica" size:17.0f];            Btn.titleLabel.textColor = [Uicolor Whitecolor];            [Btn addtarget:self Action: @selector (buttonclicked:) forcontrolevents:uicontroleventtouchupinside]; if (_otherbuttontitles = = Nil && _cancelbuttontitle! = nil) {[Btn Settitle:_cancelbutto            Ntitle Forstate:uicontrolstatenormal]; } else {[btn settitle:[_otherbuttontitles objectaTINDEX:0] Forstate:uicontrolstatenormal];            } btn.tag = 0;            Btn.layer.cornerRadius = 5;            [Btnview ADDSUBVIEW:BTN];        [BTN release];            } else if (_otherbuttontitles && [_otherbuttontitles count] = = 1) {//-show two buttons            -Set the relevant properties of the OK button cgfloat StartX = (_backview.frame.size.width-mbtnwidth*2-20)/2;            UIButton *otherbtn = [[UIButton alloc]initwithframe:cgrectmake (StartX, 0, Mbtnwidth, mbtnheight)];            Otherbtn.backgroundcolor = Rgba_color (36, 193, 64, 1);            OtherBtn.titleLabel.font = [Uifont fontwithname:@ "Helvetica" size:17.0f];            OtherBtn.titleLabel.textColor = [Uicolor Whitecolor];            [Otherbtn settitle:[_otherbuttontitles objectatindex:0] forstate:uicontrolstatenormal];            OtherBtn.layer.cornerRadius = 5;            [Otherbtn addtarget:self Action: @selector (buttonclicked:) forcontrolevents:uicontroleventtouchupinside]; OTherbtn.tag = 0;            [Btnview ADDSUBVIEW:OTHERBTN];            [OTHERBTN release];                        StartX + = mbtnwidth+20; -Set the relevant properties of the Cancel button UIButton *cancelbtn = [[UIButton alloc]initwithframe:cgrectmake (StartX, 0, Mbtnwidth, Mbtnheig            HT)];            Cancelbtn.backgroundcolor = Rgba_color (36, 193, 64, 1);            CancelBtn.titleLabel.font = [Uifont fontwithname:@ "Helvetica" size:17.0f];            CancelBtn.titleLabel.textColor = [Uicolor Whitecolor];            [Cancelbtn Settitle:_cancelbuttontitle Forstate:uicontrolstatenormal];            CancelBtn.layer.cornerRadius = 5;            [Cancelbtn addtarget:self Action: @selector (buttonclicked:) forcontrolevents:uicontroleventtouchupinside];            Cancelbtn.tag = 1;            [Btnview ADDSUBVIEW:CANCELBTN];        [CANCELBTN release];        } [_backview Addsubview:btnview];    [Btnview release];        } else {CGRect rc = _backview.frame; Rc.size.height-= MHEaderheight;    _backview.frame = RC;    } Uicontrol *touchview = [[Uicontrol alloc] initWithFrame:self.frame];    [TouchView addtarget:self Action: @selector (Touchviewclickdown) Forcontrolevents:uicontroleventtouchdown];    Touchview.frame = Self.frame;    [Self addsubview:touchview];    [TouchView release];         _backview.center = Self.center;        [Self addsubview:_backview];    if (!_isshow) [Customalertview Exchangeout:_backview dur:0.5];            if (self.delegate) {if ([Self.delegate respondstoselector: @selector (Willpresentcustomalertview:)]) {        [Self.delegate willpresentcustomalertview:self]; } [[Nsnotificationcenter defaultcenter] postnotificationname:kbcalertviewpresentnotify object:nil userInfo:    NIL]; }}-(void) touchviewclickdown{if (self.delegate) {if ([Self.delegate respondstoselector: @selector (Hidecurren        Tkeyboard)]) {[Self.delegate hidecurrentkeyboard]; }}}//-InMessage area Settings custom control-(void) Addcustomersubview: (UIView *) view{[Self.customerviewstobeadd Addobject:view];}    -(void) buttonclicked: (ID) sender{UIButton *btn = (UIButton *) sender;    _isshow = NO; if (BTN) {if (self.delegate && [self.delegate respondstoselector: @selector (alertview:clickedbuttonatind        Ex:)]) {[self.delegate alertview:self ClickedButtonAtIndex:btn.tag];    } [self Removefromsuperview];    }}-(void) closebtnclicked: (id) sender{_isshow = NO; if (self.delegate && [self.delegate respondstoselector: @selector (alertviewclosed:)]) {[Self.delegate al    Ertviewclosed:self]; } [self Removefromsuperview];}    -(void) show{[self layoutsubviews];            if (!_isshow) [[[UIApplication sharedapplication].delegate window] addsubview:self]; _isshow = YES;}    -(void) dealloc{[_backview release];    [_customerviewstobeadd release];    Self.titlelabel = nil;    Self.titlebackgroundview = nil; Self.titLeicon = nil;  [Super Dealloc]; }//-Alertview popup animation + (void) Exchangeout: (UIView *) Changeoutview dur: (cftimeinterval) dur{cakeyframeanimation * Animatio    N        Animation = [Cakeyframeanimation animationwithkeypath:@ "transform"];    Animation.duration = dur;    Animation.removedoncompletion = NO;        Animation.fillmode = Kcafillmodeforwards;        Nsmutablearray *values = [Nsmutablearray array];    [Values Addobject:[nsvalue Valuewithcatransform3d:catransform3dmakescale (0.1, 0.1, 1.0)];    [Values Addobject:[nsvalue Valuewithcatransform3d:catransform3dmakescale (1.2, 1.2, 1.0)];    [Values Addobject:[nsvalue Valuewithcatransform3d:catransform3dmakescale (0.9, 0.9, 0.9)];        [Values Addobject:[nsvalue Valuewithcatransform3d:catransform3dmakescale (1.0, 1.0, 1.0)];    Animation.values = values;        Animation.timingfunction = [camediatimingfunction functionwithname: @ "Easeineaseout"]; [Changeoutview.layer addanimation:animation forkey:nil];} @end


iOS custom Alertview, inherited from UIView, can add child view, title picture + text

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.