internal override func collectionView(
_ collectionView: UICollectionView,
cellForItemAt indexPath: IndexPath
) -> UICollectionViewCell
{
let cell = collectionView.dequeueReusableCell(
withReuseIdentifier: CategoriesCollectionViewCell.reuseIdentifier,
for: indexPath
) as! CategoriesCollectionViewCell
let randomIndex = indexPath.item % CategoriesPlaceholder.images.count
cell.configure(
withImage: UIImage(named: CategoriesPlaceholder.images[randomIndex])!,
andTitle: CategoriesPlaceholder.titles[randomIndex]
)
return cell
}
internal final class CategoriesCollectionViewCell: UICollectionViewCell {
// =====================================
// MARK: - Configure
// =====================================
internal func configure(withImage image: UIImage?, andTitle title: String) {
illustrationCircle.image = image
self.title.text = title
}
Do not call the dispatch_sync function from a task that is executing on the same queue that you pass to your function call. Doing so will deadlock the queue. If you need to dispatch to the current queue, do so asynchronously using the dispatch_async function.
internal final class ModalAnimator: NSObject, UIViewControllerAnimatedTransitioning {
private var isPresenting: Bool
private let duration: TimeInterval = 3
internal init(isPresenting: Bool) {
self.isPresenting = isPresenting
}
internal func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return duration
}
internal func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
guard let fromVC = transitionContext.viewController(forKey: .from),
let toVC = transitionContext.viewController(forKey: .to),
let snapshot = toVC.view.snapshotView(afterScreenUpdates: true)
else { return }
let containerView = transitionContext.containerView
snapshot.frame = fromVC.view.frame
containerView.addSubview(toVC.view)
containerView.addSubview(snapshot)
fromVC.view.isHidden = true
UIView.animate(
withDuration: duration,
animations: { snapshot.transform = CGAffineTransform(rotationAngle: .pi)},
completion: { _ in
fromVC.view.isHidden = false
snapshot.removeFromSuperview()
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
})
}
}
class CustomProgressBar: UIView {
var proportion = 1.0 {
didSet { invalidateIntrinsicContentSize() }
}
override var intrinsicContentSize: CGSize {
return CGSize(width: proportion, height: 1.0)
}
}
frame.width в кастомном view в layoutSubviews
class StackProgressView: UIView {
var proportion = 1.0
override var intrinsicContentSize: CGSize {
return CGSize(width: proportion, height: 1.0)
}
}
let stack = UIStackView(frame: CGRect(origin: .zero, size:CGSize(width: 500.0, height: 20.0)))
stack.distribution = .fillProportionally
stack.axis = .horizontal
stack.spacing = 5.0
let walk = StackProgressView(frame: .zero)
walk.backgroundColor = UIColor(red: 162.0 / 255.0, green: 221.0 / 255.0, blue: 239.0 / 255.0, alpha: 1.0)
walk.proportion = 24.5
walk.layer.allowsEdgeAntialiasing = true
walk.layer.cornerRadius = 5.0
walk.layer.maskedCorners = [.layerMinXMinYCorner, .layerMinXMaxYCorner]
let aerobic = StackProgressView(frame: .zero)
aerobic.backgroundColor = UIColor(red: 69.0 / 255.0, green: 187.0 / 255.0, blue: 223.0 / 255.0, alpha: 1.0)
aerobic.proportion = 17.1
let run = StackProgressView(frame: .zero)
run.backgroundColor = UIColor(red: 40.0 / 255.0, green: 112.0 / 255.0, blue: 133.0 / 255.0, alpha: 1.0)
run.proportion = 58.3
run.layer.allowsEdgeAntialiasing = true
run.layer.cornerRadius = 5.0
run.layer.maskedCorners = [.layerMaxXMinYCorner, .layerMaxXMaxYCorner]
stack.addArrangedSubview(walk)
stack.addArrangedSubview(aerobic)
stack.addArrangedSubview(run)
Сколько бы я не искал, пытался найти, подробной информации и примера кода нигде нет.
if #available(iOS 12, *) {
textField.textContentType = .oneTimeCode
}
adjustsFontForContentSizeCategory
у UIFont
, которое не зря по умолчанию выставлено в true
.preferredFont(forTextStyle:)
, preferredFont(forTextStyle:compatibleWith:)
и от UIFontMetrics
включает это свойство, для остальных шрифтов - отключён. Вот ваш способ и сработал. UITableView
не пропускает ивенты UIEvent
во время скролла своим сабвьюхам. Поэтому ваш UIDatePicker
и не получает никаких касаний(ивентов UIEvent
), до тех пор, пока не остановить таблицу.func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView?
у UITableView
;auth
всего лишь возвращает инстанц класса FIRAuth
Собственно все ваши currentUser
тут присутствуют. Думаю теперь вопросов быть не должно. @implementation FIRAuth {
/** @var _currentUser
@brief The current user.
*/
FIRUser *_currentUser;
/** @var _firebaseAppName
@brief The Firebase app name.
*/
NSString *_firebaseAppName;
/** @var _listenerHandles
@brief Handles returned from @c NSNotificationCenter for blocks which are "auth state did
change" notification listeners.
@remarks Mutations should occur within a @syncronized(self) context.
*/
NSMutableArray<FIRAuthStateDidChangeListenerHandle> *_listenerHandles;
/** @var _keychain
@brief The keychain service.
*/
FIRAuthKeychain *_keychain;
/** @var _lastNotifiedUserToken
@brief The user access (ID) token used last time for posting auth state changed notification.
*/
NSString *_lastNotifiedUserToken;
/** @var _autoRefreshTokens
@brief This flag denotes whether or not tokens should be automatically refreshed.
@remarks Will only be set to @YES if the another Firebase service is included (additionally to
Firebase Auth).
*/
BOOL _autoRefreshTokens;
/** @var _autoRefreshScheduled
@brief Whether or not token auto-refresh is currently scheduled.
*/
BOOL _autoRefreshScheduled;
/** @var _isAppInBackground
@brief A flag that is set to YES if the app is put in the background and no when the app is
returned to the foreground.
*/
BOOL _isAppInBackground;
/** @var _applicationDidBecomeActiveObserver
@brief An opaque object to act as the observer for UIApplicationDidBecomeActiveNotification.
*/
id<NSObject> _applicationDidBecomeActiveObserver;
/** @var _applicationDidBecomeActiveObserver
@brief An opaque object to act as the observer for
UIApplicationDidEnterBackgroundNotification.
*/
id<NSObject> _applicationDidEnterBackgroundObserver;
}
class Auth {
class func auth() -> FIRAuth { ... }
...
}
class FIRAuth {
var currentUser: FIRUser?
...
}
class FIRUser {
var providerData: [Int : {что-то}]
...
}
Auth.auth().currentUser?.providerData[indexPath.row]
FUIAuth.defaultAuthUI()
возвращает опционал. Почему бы и не продолжить цепочку. Продолжаем: FUIAuth.defaultAuthUI()?.handleOpen(url, sourceApplication: sourceApplication)
Но как не странно этот метод тоже возвращает опционал и мы просто хотим себя от этого обезопасить и сказать, что если на последнем методе тоже будет опционал, то верни правую часть, то бишь false. В итоге получаем общую картину: FUIAuth.defaultAuthUI()?.handleOpen(url, sourceApplication: sourceApplication) ?? false
super.tableView.indexPath(for: self)
@IBAction func change(sender: UIButton) {
for case let mycell as MyCustomCell in tableView.visibleCells where mycell.changeButton === sender {
let indexPath = tableView.indexPath(for: myCell)
// ...
}
}
let str = "Привет Как дела" // Внутренняя кодировка Свифта utf-32
let cp1251Data = str.data(using: .windowsCP1251)
let utf8Data = str.data(using: .utf8)
cp1251Data.count // 15
utf8Data.count // 28
// ***********************************
let session = URLSession.shared
var URL = URL(string: "https://greatcomments.server/add")!
var request = URLRequest(url: URL)
request.httpMethod = "POST"
// Headers
request.addValue("application/x-www-form-urlencoded; charset=windows-1251", forHTTPHeaderField: "Content-Type")
// Form URL-Encoded Body
let bodyParameters = [
"comment": "Проверка",
]
let bodyString = bodyParameters.queryParameters
request.httpBody = bodyString.data(using: . win1251, allowLossyConversion: true)
let task = session.dataTask(with: request, completionHandler: { (data: Data?, response: URLResponse?, error: Error?) -> Void in
if (error == nil) {
// Success
let statusCode = (response as! HTTPURLResponse).statusCode
print("URL Session Task Succeeded: HTTP \(statusCode)")
}
else {
// Failure
print("URL Session Task Failed: %@", error!.localizedDescription);
}
})
task.resume()
session.finishTasksAndInvalidate()
// ***********************************
protocol URLQueryParameterStringConvertible {
var queryParameters: String {get}
}
extension Dictionary : URLQueryParameterStringConvertible {
var queryParameters: String {
var parts: [String] = []
for (key, value) in self {
let part = String(format: "%@=%@",
String(describing: key).win1251Encoded,
String(describing: value).win1251Encoded)
parts.append(part as String)
}
return parts.joined(separator: "&")
}
}
extension URL {
func appendingQueryParameters(_ parametersDictionary : [String: String]) -> URL {
let URLString : String = String(format: "%@?%@", self.absoluteString, parametersDictionary.queryParameters)
return URL(string: URLString)!
}
}
// Раньше Swift(Foundation) позволял любую строку закодировать в url-encode в любой кодировке.
// Сейчас же де факто это можно лишь сделать в utf-8.
// Видимо Apple аргументирует это тем, что utf-8 - это стандарт в вебе.
// Да всех остальных случаев нужно писать такую функцию самому.
// Ниже кодировка в url-encode в windows-1251
extension CharacterSet {
static let rfc3986Unreserved = CharacterSet(charactersIn: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~=&+")
}
extension String.Encoding {
static let win1251 = String.Encoding(rawValue: CFStringConvertEncodingToNSStringEncoding(CFStringEncoding(CFStringEncodings.windowsCyrillic.rawValue)))
}
extension String {
func addingPercentEncoding(withAllowedCharacters characterSet: CharacterSet, using encoding: String.Encoding) -> String {
let stringData = self.data(using: encoding, allowLossyConversion: true) ?? Data()
let percentEscaped = stringData.map {byte->String in
if characterSet.contains(UnicodeScalar(byte)) {
return String(UnicodeScalar(byte))
} else if byte == UInt8(ascii: " ") {
return "+"
} else {
return String(format: "%%%02X", byte)
}
}.joined()
return percentEscaped
}
var win1251Encoded: String {
return self.addingPercentEncoding(withAllowedCharacters: .rfc3986Unreserved, using: . win1251)
}
}
class Printer {
static func mustprint() {
print ("was printed")
}
}
Printer.mustprint()
class Printer {
func mustprint() {
print ("was printed")
}
}
let printer = Printer(); printer.mustprint()