如何将以下功能转换为swift 3?目前收到Binary operator '..<' cannot be applied to operands of type 'Int' and 'Self.IndexDistance'错误.
extension MutableCollection where Index == Int {
/// Shuffle the elements of `self` in-place.
mutating func shuffleInPlace() {
// empty and single-element collections don't shuffle
if count < 2 { return }
for i in 0..<count - 1 { //error takes place here
let j = Int(arc4random_uniform(UInt32(count - i))) + i
guard i != j else { continue }
swap(&self[i], &self[j])
} …Run Code Online (Sandbox Code Playgroud) 我有一个启用分页的UICollectionView内部UIViewController.由于一些奇怪的原因,collectionView.scrollToItem当方向collectionview是,vertical但不是方向时工作horizontal.这有什么我做错了或者这应该发生吗?
//Test scrollToItem
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let i = IndexPath(item: 3, section: 0)
collectionView.reloadData()
collectionView.scrollToItem(at: i, at: .top, animated: true)
print("Selected")
}
Run Code Online (Sandbox Code Playgroud) 如何在键入时显示功能的简要说明,如下图所示?我尝试过很多不同的选择都失败了.
选项+点击有效,但这不是我想要的.
选项1
/// Testing...
/// - returns: false
func testing()->Bool{
return false
}
Run Code Online (Sandbox Code Playgroud)
选项2
/**
Testing option two
*/
func testing()->Bool{
return false
}
Run Code Online (Sandbox Code Playgroud)
此问题已在Xcode 9中修复
是否可以检测触摸并获取UIViewController当前用作previewingContext3D Touch视图控制器的触摸位置?(当触摸从左向右移动时,我想更改预览控制器内的图像)
我已经尝试了两个touchesBegan,touchesMoved但没有一个被解雇.
class ThreeDTouchPreviewController: UIViewController {
func getLocationFromTouch(touches: Set<UITouch>) -> CGPoint?{
guard let touch = touches.first else { return nil }
return touch.location(in: self.view)
}
//Not fired
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
let location = getLocationFromTouch(touches: touches)
print("LOCATION", location)
}
//Not fired
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
let location = getLocationFromTouch(touches: touches)
print("LOCATION", location)
}
}
Run Code Online (Sandbox Code Playgroud)
甚至尝试添加UIPanGesture.
尝试复制FaceBook的3D Touch功能,用户可以从左向右移动手指以更改当前显示的图像.上下文视频:https://streamable.com/ilnln
出于某些奇怪的原因,HKActivitySummaryQuery为每个摘要执行返回的日期组件是落后的一天.查询从正确的日期返回数据,但dateComponents数据的日期落后一天.我已经尝试设置时区和语言环境,但结果保持不变.
struct ActivitySummary {
init?(_ summary: HKActivitySummary) {
var calendar = Calendar.current
calendar.timeZone = TimeZone.current
guard let date = summary.dateComponents(for: calendar).date else { return nil }
print("ORIGINAL: ", date.description(with: Locale.current))
//Expected: Tuesday, January 30, 2018 at 7:00:00 PM Eastern Standard Time
//Results: Monday, January 29, 2018 at 7:00:00 PM Eastern Standard Time
let other = calendar.dateComponents( [ .year, .month, .day ], from: date)
print("START OF DAY: ", date.startOfDay.description(with: Locale.current))
//Expected: Tuesday, January 30, 2018 at …Run Code Online (Sandbox Code Playgroud) 我目前有一个UICollectionViewusing UICollectionViewCompositionalLayout. 我想在滚动/滚动停止时为当前可见单元格中的一些视图设置动画。
不幸的是,它似乎orthogonalScrollingBehavior在一个部分上设置了任何东西,但.none劫持了UICollectionView随附的UIScrollView委托方法。
想知道目前是否有任何解决方法?获取分页行为和UIScrollView委托?
enum Section {
case main
}
override func awakeFromNib() {
super.awakeFromNib()
collectionView.collectionViewLayout = createLayout()
collectionView.delegate = self
}
func configure() {
snapshot.appendSections([.main])
snapshot.appendItems(Array(0..<10))
dataSource.apply(snapshot, animatingDifferences: false)
}
private func createLayout() -> UICollectionViewLayout {
let leadingItem = NSCollectionLayoutItem(
layoutSize: NSCollectionLayoutSize(
widthDimension: .fractionalWidth(1.0),
heightDimension: .fractionalHeight(1.0))
)
leadingItem.contentInsets = .zero
let containerGroup = NSCollectionLayoutGroup.horizontal(
layoutSize: NSCollectionLayoutSize(
widthDimension: .fractionalWidth(1.0),
heightDimension: .fractionalHeight(1.0)
),
subitems: [leadingItem]) …Run Code Online (Sandbox Code Playgroud) 是否可以使struct和/或typealias符合@objc?我希望创建可选的协议功能,一个返回a struct,另一个返回a typealias。
public typealias SwiperData = (image: UIImage, title: String)
public struct SwiperPeekViewControllers{
public var parentViewController: UIViewController!
public var contentViewController: UIViewController!
public init(parentVC: UIViewController, contentVC: UIViewController){
parentViewController = parentVC
contentViewController = contentVC
}
}
Run Code Online (Sandbox Code Playgroud)
协议
@objc public protocol SwiperPeekViewDelegate: class{
func didUndoAction(index: Int, dataSource: SwiperData)
// Method cannot be a member of an @objc protocol because the type of the parameter 2 cannot be represented in Objective-C
func swiperPeekViewControllers()->SwiperPeekViewControllers
func swiperPeekViewSize()->CGSize …Run Code Online (Sandbox Code Playgroud) 在我的swift应用程序中,我有一个像这样的搜索栏:
lazy var searchBar = UISearchBar(frame: CGRectMake(0, 0, 0, 0))
searchBar.delegate = self
searchBar.showsCancelButton = true
searchBar.tintColor = UIColor.blackColor()
searchBar.spellCheckingType = .No
searchBar.autocapitalizationType = .None
searchBar.autocorrectionType = .No
searchBar.placeholder = "Suchbegriff eingeben ..."
searchBar.sizeToFit()
Run Code Online (Sandbox Code Playgroud)
如何为取消按钮设置另一种色调颜色作为整个搜索栏的色调?
我想更改与数组索引匹配的 UITextView 中特定文本的文本颜色。我能够稍微修改这个答案,但不幸的是,每个匹配短语的文本颜色只更改一次。
var chordsArray = ["Cmaj", "Bbmaj7"]
func getColoredText(textView: UITextView) -> NSMutableAttributedString {
let text = textView.text
let string:NSMutableAttributedString = NSMutableAttributedString(string: text)
let words:[String] = text.componentsSeparatedByString(" ")
for word in words {
if (chordsArray.contains(word)) {
let range:NSRange = (string.string as NSString).rangeOfString(word)
string.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: range)
}
}
chords.attributedText = string
return string
}
Run Code Online (Sandbox Code Playgroud)
结果

我目前正在使用此答案提供的此扩展程序将html转换为字符串中的字符串UITextView.一切都很完美,但由于某些奇怪的原因,NSFontAttributeName在此过程中不会应用于字符串.我有什么问题吗?(或者我应该在使用NSAttributedString后面的html解析字符串后应用?如果是这样,是否可以将属性应用于NSAttributeString?).
PS.使用时字体大小不会改变,html2String但html中的链接会被更长时间识别UITextView
extension String {
var html2AttributedString: NSAttributedString? {
guard
let data = dataUsingEncoding(NSUTF8StringEncoding)
else { return nil }
do {
return try NSAttributedString(data: data, options: [NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType,NSCharacterEncodingDocumentAttribute:NSUTF8StringEncoding, NSFontAttributeName : UIFont.systemFontOfSize(17.0)], documentAttributes: nil)
} catch let error as NSError {
print(error.localizedDescription)
return nil
}
}
var html2String: String {
return html2AttributedString?.string ?? ""
}
}
cell.desc.attributedText = apiData[currentIndex].description!.html2AttributedString //Font attribute not recognized
cell.desc.text = apiData[currentIndex].description!.html2String //Font recognized by …Run Code Online (Sandbox Code Playgroud) 我试图在其预期操作完成后解除模态,但我不知道目前如何在 SwiftUI 中完成此操作。此模式由@State值更改触发。是否可以通过观察各种通知来更改此值?
想要的动作:Root -> Initial Modal -> Presents Children -> Dismiss modal from any child
以下是我尝试过的
错误:转义闭包捕获变异的“self”参数
struct AContentView: View {
@State var pageSaveInProgress: Bool = false
init(pages: [Page] = []) {
// Observe change to notify of completed action
NotificationCenter.default.publisher(for: .didCompletePageSave).sink { (pageSaveInProgress) in
self.pageSaveInProgress = false
}
}
var body: some View {
VStack {
//ETC
.sheet(isPresented: $pageSaveInProgress) {
ModalWithChildren()
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
ModalWithChildren 测试动作
Button(action: {
NotificationCenter.default.post(
name: .didCompletePageSave, object: nil)},
label: …Run Code Online (Sandbox Code Playgroud) 是否有可能返回数组tuples作为AnyObject?或我将不得不封装tuple内的变量class,然后返回class?
目前的结构
public typealias Changes = (id:Int!, cors:Bool!)
struct ClientReturn{
var error: NSError?
var json: JSON?
var mutableReturn: AnyObject?
var pageResults: PageResults?
}
class func Changes(api_key: String!, startDate: String?, endDate:String?,
completion: (ClientReturn) -> ()) -> (){
//content
}
Client.Changes(api_key, startDate: nil, endDate: nil){
apiReturn in
var aReturn = apiReturn;
var changesArray = [Changes]()
for(var i = 0; i < apiReturn.json!["results"].count; i++ ){
let json = apiReturn.json!["results"]
changesArray.append((id: json[i]["id"].int, cors: json[i]["cors"].bool)) …Run Code Online (Sandbox Code Playgroud) 我的代码:
@IBAction func handlePan(gesture: UIPanGestureRecognizer) {
let transition = gesture.translationInView(self.view)
switch gesture.state{
case .Changed:
if let view = gesture.view {
view.center = CGPoint(x: view.center.x + transition.x, y: view.center.y + transition.y)
}
gesture.setTranslation(CGPointZero, inView: self.view)
default:break
}
}
Run Code Online (Sandbox Code Playgroud)
所以我可以在屏幕上拖动一个大按钮。一切正常,直到我注释掉gesture.setTranslation(CGPointZero, inView: self.view)。
我以为一行代码只会告诉应用程序记住屏幕上按钮的最后位置并下次从那里移动,但是......
然后我在模拟器上再次运行该项目,当我单击该按钮并尝试移动一点时,该按钮只是朝同一方向飞行并消失在屏幕外,为什么?