网络请求失败——点我重试

网络请求失败——点我重试_第1张图片

创建一个RequestFailView继承自UIView,默认高度设置为0,就是不显示,不显示不用hidden为true是因为hidden后高度还在,如果你把RequestFailView设置为tableview的footerView时,虽然看不到,但是会看到高度还在,拉到底会多出一段。并把真正的高度保存在preHeight

public class RequestFailView: UIView {
    private var preHeight: CGFloat?
    override public init(frame: CGRect) {
        super.init(frame: frame)
        self.preHeight = frame.height
        self.height = 0        
    }
    required public init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}```
创建一个button,布局居中,并设置选中状态和正常状态的title

private lazy var button:UIButton = {
let aBtn = UIButton(type: .Custom)
aBtn.frame = CGRectMake(self.width/2 - 50, self.preHeight!/2 - 25, 100, 50)
aBtn.setTitle("点我重试", forState: .Normal)
aBtn.setTitle("加载中...", forState: .Selected)
aBtn.setTitleColor(UIColor.lightGrayColor(), forState: .Normal)
aBtn.addTarget(self, action: #selector(RequestFailView.buttonClickedAction), forControlEvents: .TouchUpInside)
return aBtn
}()```
创建一个Closure,用于作为响应事件的接口

public typealias ClosureType = () -> ()
    
public var ButtonClosure:ClosureType?```
button点击事件,点击一次后,设置为选中状态,并在“加载中...”的选中状态时,不响应点击事件

@objc private func buttonClickedAction() {
//在选中状态不能响应点击事件
if self.button.selected == true {
return
}
if ButtonClosure != nil {
self.button.selected = true
ButtonClosure!()
}
}

显示view,“点我重试”

public func show() {
self.button.selected = false
self.height = preHeight!
self.addSubview(self.button)
}

隐藏view

public func hidden() {
self.height = 0
self.button.removeFromSuperview()
}```
在tableview中应用

lazy var footerView:RequestFailView = {
    let aView = RequestFailView(frame: CGRectMake(0,0,screen_width,150))
    aView.ButtonClosure = {
            [unowned self] in//避免循环引用
           //网络请求
        }
    self.tableView.tableFooterView = aView
    return aView
}()

请求成功

self.footerView.hidden()```
请求失败

self.footerView.show()```
为了使代码更加可读性,可将ButtonClosure改为代理模式

你可能感兴趣的:(网络请求失败——点我重试)