自定义UIAlertView block实现点击事件

使用系统自带的AlertView时候难免需要实现代理方法,不如使用block方便,这里通过UIView自定义一个AlertView,可以无按钮,一个按钮,两个按钮三种形式

效果

下面先看一下效果图吧


image

image

image

使用


LYAlertView.show("title", "message")

LYAlertView.show("title", "message", "btnTitle", {
//点击按钮
})
LYAlertView.show("title", "message", "leftTitle", "rightTitle", {
//右按钮
}, { 
//左按钮
})

源码

下面直接将代码展示出来,你可以选择借鉴或者直接复制下面代码,或者使用LYTools

//
//  LYAlertView.swift
//  qixiaofu
//   _
//  | |      /\   /\
//  | |      \ \_/ /
//  | |       \_~_/
//  | |        / \
//  | |__/\    [ ]
//  |_|__,/    \_/
//
//  Created by ly on 2017/6/29.
//  Copyright © 2017年 qixiaofu. All rights reserved.
//

import UIKit
import QuartzCore

let KTitltOringy:CGFloat = 15.0
let KTitltHeight:CGFloat = 25.0
let KContentOringy:CGFloat = 30.0
let KBetweenLableOffset:CGFloat = 20.0
let KAlertWidth:CGFloat = 245.0
let KAlertHeight:CGFloat = 160.0

typealias leftBlock = () ->()
typealias rightBlock = ()->()
typealias DelaydismissBlock = ()->()


class LYAlertView: UIView {

var leftblock : leftBlock?
var rightblock : rightBlock?
var dismissblock : DelaydismissBlock?
var alertTitleLabel : UILabel?
var alertContentLabel : UILabel?
var leftBtn : UIButton?
var rightBtn : UIButton?
var backImageView:UIView?

var delayTime:Int64 = 0

override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor.black.withAlphaComponent(0.3)
self.addTapActionBlock { 
if (self.dismissblock != nil){
self.dismissblock!()
}
self.removeFromSuperview()
}
}

//没有按钮
func initBody(title:String,message:String,DismissDelay:Int64)
{
self.delayTime = DismissDelay
self.initTwoBtn(title: title, message: message, cancelButtonTitle: "", otherButtonTitle: "")
}
//一个按钮
func initOneBtn(title:String,message:String,ButtonTitle:String)
{
self.initTwoBtn(title: title, message: message, cancelButtonTitle: "", otherButtonTitle: ButtonTitle)
}
//两个按钮
func initTwoBtn(title:String,message:String,cancelButtonTitle:String,otherButtonTitle:String) {

//super.init(frame: CGRectZero)
backImageView = UIImageView(frame: CGRect(x:0, y:0, width:KAlertWidth, height:KAlertHeight))
backImageView?.center = self.center
backImageView?.backgroundColor = UIColor.RGBS(s: 250)
backImageView?.layer.cornerRadius = 15.0
backImageView?.isUserInteractionEnabled = true
self.addSubview(backImageView!)


alertTitleLabel = UILabel(frame: CGRect(x:0, y:KTitltOringy, width:KAlertWidth, height:KTitltHeight))
alertTitleLabel!.font = UIFont.boldSystemFont(ofSize: 20.0)
alertTitleLabel!.textColor = UIColor(red:56.0/255.0,green:64.0/255.0,blue:71.0/255.0,alpha:1)
backImageView?.addSubview(alertTitleLabel!)


let contentLabelWidth = KAlertWidth - 16
alertContentLabel = UILabel(frame:CGRect(x:(KAlertWidth - contentLabelWidth) * 0.5, y:alertTitleLabel!.frame.maxY, width:contentLabelWidth, height:60))
alertContentLabel!.numberOfLines = 0
alertContentLabel!.textAlignment = NSTextAlignment.center
alertTitleLabel!.textAlignment = NSTextAlignment.center
alertContentLabel!.textColor = UIColor(red:127.0/255.0,green:127.0/255.0,blue:127.0/255.0,alpha:1)
alertContentLabel!.font = UIFont.systemFont(ofSize: 15.0)
backImageView?.addSubview(alertContentLabel!)

alertTitleLabel!.text = title as String
alertContentLabel!.text = message as String

let KSingleButtonWidth:CGFloat = 160.0
let kCoupleButtonWidth:CGFloat = 107.0
let kButtonHeight:CGFloat = 40.0
let kButtonBottomOffset:CGFloat = 10.0

//没有按钮
if cancelButtonTitle.isEmpty && otherButtonTitle.isEmpty{
alertTitleLabel?.frame.origin.y = KTitltOringy+20
alertContentLabel?.frame.size.height = 100
if(self.delayTime==0){
self.delayTime = 2
}
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double((Int64)(UInt64(self.delayTime) * NSEC_PER_SEC)) / Double(NSEC_PER_SEC), execute: {
if (self.dismissblock != nil){
self.dismissblock!()
}
self.removeFromSuperview()
})
return
}else if !cancelButtonTitle.isEmpty && !otherButtonTitle.isEmpty {
//两个按钮
let leftBtnFrame = CGRect(x:(KAlertWidth - 2 * kCoupleButtonWidth - kButtonBottomOffset) * 0.5, y:KAlertHeight - kButtonBottomOffset/2.0 - kButtonHeight, width:kCoupleButtonWidth, height:kButtonHeight);
let rightBtnFrame = CGRect(x:leftBtnFrame.maxX + kButtonBottomOffset, y:KAlertHeight - kButtonBottomOffset/2.0 - kButtonHeight, width:kCoupleButtonWidth, height:kButtonHeight);
leftBtn = UIButton(frame:leftBtnFrame);
rightBtn = UIButton(frame:rightBtnFrame)

//        rightBtn!.setBackgroundImage( UIImage(named: "button_orange_normal") ,for:UIControlState.normal)
//        rightBtn!.setBackgroundImage( UIImage(named: "button_orange_click") ,for:UIControlState.selected)
rightBtn!.setTitle(otherButtonTitle as String, for: UIControlState.normal)
rightBtn!.titleLabel!.font = UIFont.boldSystemFont(ofSize: 14)
rightBtn!.setTitleColor(UIColor.RGBS(s: 33),for:UIControlState.normal)
rightBtn!.addTarget(self, action: #selector(LYAlertView.rightBtnClicked), for: UIControlEvents.touchUpInside)
rightBtn!.layer.masksToBounds = true
rightBtn!.layer.cornerRadius = 3.0
backImageView?.addSubview(rightBtn!)

//按钮上面的线
let topLine = UIView.init(frame: CGRect(x:0, y:KAlertHeight - kButtonBottomOffset - kButtonHeight, width:KAlertWidth, height:1.5))
topLine.backgroundColor = UIColor.RGBS(s: 240)
backImageView?.addSubview(topLine)


//按钮之间的线
let bottomLine = UIView.init(frame: CGRect(x:leftBtnFrame.maxX + kButtonBottomOffset/2.0, y:KAlertHeight - kButtonBottomOffset - kButtonHeight, width:1.5, height:kButtonHeight + kButtonBottomOffset))
bottomLine.backgroundColor = UIColor.RGBS(s: 240)
backImageView?.addSubview(bottomLine)

}else{
//按钮上面的线
let topLine = UIView.init(frame: CGRect(x:0, y:KAlertHeight - kButtonBottomOffset - kButtonHeight, width:KAlertWidth, height:1.5))
topLine.backgroundColor = UIColor.RGBS(s: 240)
backImageView?.addSubview(topLine)
//一个按钮
leftBtn = UIButton(frame:CGRect(x:(KAlertWidth-KSingleButtonWidth)/2, y:KAlertHeight - kButtonBottomOffset/2.0 - kButtonHeight, width:KSingleButtonWidth, height:kButtonHeight))
}

//            leftBtn?.setBackgroundImage(UIImage(named: "button_white_normal"), for: UIControlState.normal)
//            leftBtn?.setBackgroundImage(UIImage(named: "button_white_clicked"), for: UIControlState.selected)
leftBtn!.setTitle(cancelButtonTitle as String, for: UIControlState.normal)
leftBtn!.titleLabel!.font = UIFont.boldSystemFont(ofSize: 14)
leftBtn!.setTitleColor(UIColor.RGBS(s: 33),for:UIControlState.normal)
leftBtn!.addTarget(self, action: #selector(LYAlertView.leftBtnClicked), for: UIControlEvents.touchUpInside)
leftBtn!.layer.masksToBounds = true
backImageView?.addSubview(leftBtn!)
leftBtn!.layer.masksToBounds = true
leftBtn!.layer.cornerRadius = 3.0
}

func leftBtnClicked(){
if (self.leftblock != nil){
self.leftblock!()
}
self.dismiss()
}

func rightBtnClicked(){
if (self.rightblock != nil){
self.rightblock!()
}
self.dismiss()
}
//MARK: - 显示
//2个按钮
class func show( _ title:String, _ message:String, _ leftTitle:String, _ rightTitle:String, _ rightClick:rightBlock? = nil, _ leftClick:leftBlock? = nil, _ dismissBlock:DelaydismissBlock? = nil)->Void{
let alert = LYAlertView.init(frame: CGRect(x:0, y:0, width:UIScreen.main.bounds.width, height:UIScreen.main.bounds.height))
alert.initTwoBtn(title: title, message: message, cancelButtonTitle: leftTitle, otherButtonTitle: rightTitle)
alert.occur(animation: true)

alert.leftblock = leftClick
alert.rightblock = rightClick
alert.dismissblock = dismissBlock
}

//1个按钮
class func show( _ title:String, _ message:String, _ leftTitle:String, _ leftClick:leftBlock? = nil, _ dismissBlock:DelaydismissBlock? = nil)->Void{
self.show(title, message, leftTitle, "", nil, leftClick, dismissBlock)
}

//0个按钮
class func show( _ title:String, _ message:String, _ dismissBlock:DelaydismissBlock? = nil)->Void{
self.show(title, message, "", "", nil, nil, dismissBlock)
}

func occur(animation:Bool) -> Void{

UIApplication.shared.keyWindow?.addSubview(self)
UIApplication.shared.keyWindow?.bringSubview(toFront: self)

if animation {

UIView.animate(withDuration: 0.1, delay: 0, options:
UIViewAnimationOptions.transitionCrossDissolve, animations: { () -> Void in
self.alpha = 1.0
self.backImageView?.layer.setAffineTransform(CGAffineTransform(scaleX: 0.9, y: 0.9))
}) { (Bool) -> Void in
UIView.animate(withDuration: 0.1, delay: 0, options: UIViewAnimationOptions.transitionCrossDissolve, animations: { () -> Void in
self.backImageView?.layer.setAffineTransform(CGAffineTransform(scaleX: 1.1, y: 1.1))
}) { (Bool) -> Void in
UIView.animate(withDuration: 0.1, delay: 0, options: UIViewAnimationOptions.transitionCrossDissolve, animations: { () -> Void in
self.backImageView?.layer.setAffineTransform(CGAffineTransform(scaleX: 0.9, y: 0.9))
}) { (Bool) -> Void in
self.backImageView?.layer.setAffineTransform(CGAffineTransform(scaleX: 1.0, y: 1.0))
}
}
}
}
}

func dismiss() -> Void{
UIView.animate(withDuration: 0.2, delay: 0, options: UIViewAnimationOptions.transitionCrossDissolve, animations: { () -> Void in
self.alpha = 0
}) { (Bool) -> Void in
self.removeFromSuperview()
}
}

required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}


}

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

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 170,598评论 25 707
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 11,658评论 4 59
  • 总的来说,这周过得还算充实。第一,在周一到周五的正常上课时间里面玩手机的情况相对上个学期来说大大减少,现在的学习节...
    kisslight阅读 136评论 0 0
  • 节气歌: 春雨惊春清谷天,夏满芒夏暑相连。秋处露秋寒霜降,冬雪雪冬小大寒。'''立春:立是开始的意思,立春就是春季...
    六耳弥猴阅读 199评论 0 0
  • 生活中存在各式激励人心的教诲,如大部分人都知道的,少壮不努力,老大徒伤悲,时间飞逝,莫负好光阴,然而,生活中却同时...
    花卷卷跑跑跑阅读 285评论 0 0