iOS UIKit框架下自带的UIAlertView在功能或者美观上,有的时候并不能满足我们的开发需求,这个时候,就可以自定义alertView。我在这里写了一个简单的自定义alertView的Demo,希望能帮助到iOS开发的小伙们。话不多说,直接上代码:
在。h里:
#import <UIKit/UIKit.h>
typedef void(^alertClick)(NSInteger index);
@interface SLAlertView : UIView
@property (nonatomic,copy) alertClick clickIndex;
- (instancetype)initWithTitle:(NSString *)title message:(NSString *)message sureBtn:(NSString *)sureTitle cancleBtn:(NSString *)cancleTitle;
- (void)show;
@end
在。m里:
#import "SLAlertView.h"
#define alertViewWidth 280 //alertView 宽
#define edge 10.0 //各个栏目之间的距离
@interface SLAlertView ()
@property (nonatomic,retain) UIView *alertView;//弹窗
@property (nonatomic,retain) UILabel *titleLbl;//title
@property (nonatomic,retain) UILabel *msgLbl;//内容
@property (nonatomic,retain) UIButton *sureBtn;//确认按钮
@property (nonatomic,retain) UIButton *cancleBtn;//取消按钮
@property (nonatomic,retain) UIView *lineView;//横线线
@property (nonatomic,retain) UIView *verLineView;//竖线
@end
@implementation SLAlertView
- (instancetype)initWithTitle:(NSString *)title message:(NSString *)message sureBtn:(NSString *)sureTitle cancleBtn:(NSString *)cancleTitle
{
if (self == [super init]) {
self.frame = [UIScreen mainScreen].bounds;
self.backgroundColor = [UIColor colorWithWhite:0.8 alpha:0.6];
self.alertView = [[UIView alloc] init];
self.alertView.backgroundColor = [UIColor whiteColor];
self.alertView.layer.cornerRadius = 8.0;
self.alertView.frame = CGRectMake(0, 0, alertViewWidth, 100);
self.alertView.layer.position = self.center;
if (title) {
self.titleLbl = [self GetAdaptiveLable:CGRectMake(2*edge, 2*edge, alertViewWidth-4*edge, 20) AndText:title andIsTitle:YES];
self.titleLbl.textAlignment = NSTextAlignmentCenter;
[self.alertView addSubview:self.titleLbl];
CGFloat titleW = self.titleLbl.bounds.size.width;
CGFloat titleH = self.titleLbl.bounds.size.height;
self.titleLbl.frame = CGRectMake((alertViewWidth-titleW)/2, 2*edge, titleW, titleH);
}
if (message) {
self.msgLbl = [self GetAdaptiveLable:CGRectMake(edge, CGRectGetMaxY(self.titleLbl.frame)+edge, alertViewWidth-2*edge, 20) AndText:message andIsTitle:NO];
self.msgLbl.textAlignment = NSTextAlignmentCenter;
[self.alertView addSubview:self.msgLbl];