小编kye*_*kye的帖子

随机阵列swift 3

如何将以下功能转换为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)

swift swift3

29
推荐指数
3
解决办法
1万
查看次数

UICollectionView滚动到不使用水平方向的项目

我有一个启用分页的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)

ios uicollectionview swift

20
推荐指数
9
解决办法
2万
查看次数

Xcode 8如何在打字时显示功能描述

如何在键入时显示功能的简要说明,如下图所示?我尝试过很多不同的选择都失败了.

在此输入图像描述

选项+点击有效,但这不是我想要的.

选项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中修复

documentation xcode ios swift

9
推荐指数
4
解决办法
3680
查看次数

在UIViewController显示为3DTouch预览时检测UITouches

是否可以检测触摸并获取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

ios swift 3dtouch

7
推荐指数
1
解决办法
244
查看次数

HKActivitySummary dateComponents落后一天

出于某些奇怪的原因,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)

ios swift healthkit

6
推荐指数
1
解决办法
173
查看次数

设置 UICollectionViewCompositionalLayout 时未调用 UIScrollView 委托方法

我目前有一个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)

ios uicollectionview uicollectionviewlayout swift

6
推荐指数
2
解决办法
1482
查看次数

如何使struct和typealias符合@objc

是否可以使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 swift-protocols

5
推荐指数
1
解决办法
3287
查看次数

UISearchBar为取消按钮设置不同的色调颜色

在我的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)

如何为取消按钮设置另一种色调颜色作为整个搜索栏的色调?

uisearchbar swift

3
推荐指数
1
解决办法
3031
查看次数

UITextView 更改特定文本的文本颜色

我想更改与数组索引匹配的 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)

结果
结果

uitextview swift swift2.1

2
推荐指数
1
解决办法
8922
查看次数

NSFontAttributeName未应用于NSAttributedString

我目前正在使用此答案提供的此扩展程序将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)

nsattributedstring ios swift

2
推荐指数
1
解决办法
2697
查看次数

SwiftUI:从子视图中关闭模式

我试图在其预期操作完成后解除模态,但我不知道目前如何在 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)

uiview ios swift swiftui combine

2
推荐指数
1
解决办法
831
查看次数

将一个元组数组作为AnyObject返回?

是否有可能返回数组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)

tuples swift

1
推荐指数
1
解决办法
187
查看次数

没有 setTranslation 的平移手势奇怪的行为

我的代码:

@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)

我以为一行代码只会告诉应用程序记住屏幕上按钮的最后位置并下次从那里移动,但是......

然后我在模拟器上再次运行该项目,当我单击该按钮并尝试移动一点时,该按钮只是朝同一方向飞行并消失在屏幕外,为什么?

gesture ios swift

0
推荐指数
1
解决办法
787
查看次数