Home Php C# Sql C C++ Javascript Python Java Go Android Git Linux Asp.net Django .net Node.js Ios Xcode Cocoa Iphone Mysql Tomcat Mongodb Bash Objective-c Scala Visual-studio Apache Elasticsearch Jar Eclipse Jquery Ruby-on-rails Ruby Rubygems Android-studio Spring Lua Sqlite Emacs Ubuntu Perl Docker Swift Amazon-web-services Svn Html Ajax Xml Java-ee Maven Intellij-idea Rvm Macos Unix Css Ipad Postgresql Css3 Json Windows-server Vue.js Typescript Oracle Hibernate Internet-explorer Github Tensorflow Laravel Symfony Redis Html5 Google-app-engine Nginx Firefox Sqlalchemy Lucene Erlang Flask Vim Solr Webview Facebook Zend-framework Virtualenv Nosql Ide Twitter Safari Flutter Bundle Phonegap Centos Sphinx Actionscript Tornado Register | Login | Edit Tags | New Questions | 繁体 | 简体


10 questions online user: 63

686
votes
answers
17 views
+10

When converting a project to use ARC what does “switch case is in protected scope” mean?

When converting a project to use ARC what does "switch case is in protected scope" mean? I am converting a project to use ARC, using Xcode 4 Edit -> Refactor -> Convert to Objective-C ARC... One of the errors I get is "switch case is in protected scope" on "some" of the switches in a switch case.

Edit, Here is the code:

the ERROR is marked on the "default" case:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"";
    UITableViewCell *cell ;
    switch (tableView.tag) {
        case 1:
            CellIdentifier = @"CellAuthor";
            cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
            if (cell == nil) {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        }
        cell.textLabel.text = [[prefQueries objectAtIndex:[indexPath row]] valueForKey:@"queryString"];
        break;
    case 2:
        CellIdentifier = @"CellJournal";
        cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        }
        cell.textLabel.text = [[prefJournals objectAtIndex:[indexPath row]] valueForKey:@"name"];

        NSData * icon = [[prefJournals objectAtIndex:[indexPath row]] valueForKey:@"icon"];
        if (!icon) {
            icon = UIImagePNGRepresentation([UIImage imageNamed:@"blank72"]);
        }
        cell.imageView.image = [UIImage imageWithData:icon];

        break;

    default:
        CellIdentifier = @"Cell";
        cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
            }
        break;
    }


    return cell;
}
up vote 652 down vote accepted favorite
沙发
+6520
+50

Surround each case itself with braces {}. That should fix the issue (it did for me in one of my projects).

我遇到了同樣的問題。這是一個可怕的錯誤消息,並且已經提交了一個錯誤(將在未來版本的編譯器中修復)以糾正它。但是,是的,C中的case語句中的範圍規則真的很奇怪。 - bbum 2011年9月27日4:12

之所以發生這種情況,是因為您在案例範圍內聲明了一個新變量。編譯器不知道這個變量應該如何作用域(它是屬於所有的switch情況還是僅僅是當前的情況?)將case的實現包裝在括號中會為變量生成一個範圍,以便編譯器可以正確管理這是一生。 - 篠原於12年6月6日15:37

+140

Hard to be sure without looking at the code, but it probably means there's some variable declaration going on inside the switch and the compiler can't tell if there's a clear path to the required dealloc point.

+90

There are 2 easy ways to solve this issue:

  • You are probably declaring variables. Move the declaration of the variables outside the switch statement
  • Put the whole case block in between curly brackets {}

The compiler can not calculate the code line when the variables are to be released. Causing this error.

+50

For me, the problem started on the middle of a switch and curly brackets did not worked out, unless you have to include {} IN ALL previous case statements. For me the error came when I had the statement

NSDate *start = [NSDate date];

in the previous case. After I deleted this, then all subsequent case statement came clean from the protected scope error message

一樣; 中間的案例錯誤。我只需要在開關上方移動變量聲明(它不依賴於案例)。我沒有必要在案例周圍添加大括號(這次)。 - eGanges 2015年2月13日18:48

+30

Before:

    case 2:
        NSDate *from = [NSDate dateWithTimeIntervalSince1970:1388552400];
        [self refreshContents:from toDate:[NSDate date]];
        break;

I moved NSDate definition before switch, and it fixed the compile problem:

NSDate *from;  /* <----------- */
switch (index) {
    ....
    case 2:
        from = [NSDate dateWithTimeIntervalSince1970:1388552400];
        [self refreshContents:from toDate:[NSDate date]];
        break;

}
+20

Declare the variables outside the switch, then instantiate them inside the case. That worked perfectly for me using Xcode 6.2

+10
default:
        CellIdentifier = @"Cell";
        cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            ***initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];***
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
            }
        break;
    }

Note: Check! The syntax of the bold & italicized line. Rectify it and you are good to go.

0

Surround with braces {} the code between the case statement and the break in each case. It worked on my code.

0
votes
answers
21 views
+10

如何在Xcode中啓用SSE3?

0

我正在嘗試構建一些在Mac上使用SSE3的C++代碼;其他固有功能全部通過#include <x86intrin.h>被拉入,但SSE3版本tmmintrin.h不是,因爲SSE顯然未啓用(__SSSE3__未定義)。特別是,我正在尋找_mm_shuffle_epi*_mm_hadd_epi*。我對內部函數和mac都很陌生,所以也許我錯過了一些東西。如何在Xcode中啓用SSE3?

非常理想:如何讓我的程序在使用SSE3內部函數的Xcode 6上編譯?

作爲備份:我可以用什麼SSE2函數來代替上述內容?

沙发
0
0

你只需要爲向量指令代碼生成選項在構建設置中設置:

enter image description here

在這個例子中SSSE3(及以下)被啓用。

請注意,您似乎對SSE3和SSSE3(又名「SSE3帶補充說明」或「MNI」)之間的混淆 - 請注意區別。

+0

這看起來像我需要(將標記)。但是,我沒有在我的項目中看到這種構建設置;這可能是因爲它是一個iOS項目? (我只想要仿真器版本的SSE,我不相信NEON說明可用)。 – Rollie 2014-10-31 02:45:37

+0

好的,那是一個不同的問題 - 在構建設置搜索框中輸入「vector」以查看可用的選項,但我甚至不知道這是否可用於iOS項目。 – 2014-10-31 07:26:46

0
votes
answers
19 views
+10

Class PLBuildVersion is implemented in both frameworks

iOS 10 / Xcode 8 GM build getting the below, never had it before on Xcode 7. Any ideas?

objc[25161]: Class PLBuildVersion is implemented in both /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator.sdk/System/Library/PrivateFrameworks/AssetsLibraryServices.framework/AssetsLibraryServices (0x12049a910) and /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator.sdk/System/Library/PrivateFrameworks/PhotoLibraryServices.framework/PhotoLibraryServices (0x1202c4210). One of the two will be used. Which one is undefined.

(NOTE: Only seems to happen in simulator, does not appear on real device).

263
votes
answers
5 views
+10

SourceKitService Terminated

I am having a issue with Xcode where the error "Source Kit Service Terminated" is popping up and all syntax highlighting and code completion is gone in Swift. How can I fix this?

Here is an example image:

enter image description here

up vote 112 down vote accepted favorite
沙发
+1120
+50

The answer to mine (Xcode6-Beta7) was simply to delete the Derived Data folder.

Preferences > Locations > Derived Data > click the arrow to open in Finder > trash it.

Hope this helps someone. There's obviously many reasons why this crash can occur.

Thank you, this fixed it. – Noura Sep 30 '14 at 18:13

Seems this fixed the problem, but also using Xcode 6.1 GM. – Flovdis Oct 6 '14 at 11:17

this fixed it for about 10 minutes, then i changed the name of a variable and it's back! – hariseldon78 Nov 14 '14 at 16:00

Not a permanent fix but just enhancement of answer.. create a shell script and run it whenever it happens rm -frd ~/Library/Developer/Xcode/DerivedData/* rm -frd ~/Library/Caches/com.apple.dt.Xcode/* – Raj Jan 24 '15 at 9:41

Did not fix my problem – Shirish Kumar Mar 2 '15 at 21:28

+350

I believe I may have found a more general purpose solution. Below are the steps I used to encourage Xcode not to produce the SourceKitService Terminated error.


The symptoms I was having:

  • When I would start up a new playground, I would receive an error about not being able to communicate with the playground (Error running playground: Failed prepare for communication with playground. See this image on twitter.
  • When I would switch the playground from OS X to iOS, I would receive another error (unfortunately I did not write that one down).
  • When I would start to type in an iOS based Swift project, attempting to use code completion/intellisense on any UIKit specific class, I would receive the SourceKitService Terminated issue in this thread.

Debugging process:

  • I started by looking through google for SourceKitService, this got very little.
  • I then started monitoring Console.app while using Xcode. This showed a couple errors:
    • IDEPlaygroundDocument: Error encountered running playground
    • com.apple.CoreSimulator.CoreSimulatorService[3952]: The runtime for the selected device is not installed.

What I did to correct this issue.

If you are only having an issue within the context of a Swift project, try this alone first. If that doesn't work, then try all of the steps further below.

  1. Open your project and change the target's deployment target to something <= 7.1.

The more lengthy and involved process. (The first 3 steps are not for sure helpful, but I did them, and so record them here)

  1. Completely delete all copies of Xcode on your system.
  2. Restart your computer.
  3. Reinstall Xcode6-beta only.
  4. Verify that you still have the issue in playground and/or projects.
  5. Open iOS Simulator.
  6. Hardware -> Device -> Manage Devices
  7. Remove all devices.
  8. Recreate all devices you want. I appended the iOS version to the end of the name, just because.
  9. Restart Xcode and the simulator.
  10. Verify that at least playgrounds no longer throw issues when switched from OS X to iOS.
  11. Open your project and change the target's deployment target to something <= 7.1.

Analysis

It appears the issue is with Xcode6 not being able to properly find, and connect, to the simulator. I have not been able to determine why this is the case, but this has allowed me to continue developing with Swift. This may have to do with the fact the simulator binaries seem to have moved.

Had similar problem : "The runtime for the selected device is not installed." error on running playground for iPhonesimulator. Step 5.~9. fixed the issue. – barley Jun 9 '14 at 16:22

As a note - Xcode 6 Beta 3 has completely resolved the issue for me. Not sure how or why. Hopefully the same is true for others. – Andrew Monshizadeh Jul 9 '14 at 13:23

Thanks for these steps. I adjusted my deployment target from 7.0 to 7.1 and that seems to have solved the issue for now. – Nick Aug 7 '14 at 1:43

Setting the deployment target to 7.0 worked for me. – Josh Brown Sep 11 '14 at 19:18

Followed all these steps but it didn't work for me. :-/ – Rohit Goyal Apr 9 '15 at 10:24

+320

You just need to delete the "ModuleCache", this is some kind of cache used by Xcode for Autocompletion.

Copy and paste the following line in the Terminal:

rm -rf ~/Library/Developer/Xcode/DerivedData/ModuleCache

This did it for me. For a while i could only get highlighting and autocomplete when I had IOS device selected in active scheme. – Wez Nov 12 '14 at 14:36

This worked for me too. According to the release notes here some of this is fixed in Xcode 6.1.1 GM seed – Jacob Harding Nov 22 '14 at 14:16

Alas, years later, and Xcode is most definitely not fixed. Using Xcode 8.1 (8B62) and still getting SourceKitServer crashes every time I click on a symbol. Have cleared derived data, have removed the ModuleCache. Restarted Xcode. Reinstalled Xcode. Installed Xcode on a new machine. Same thing happens. Xcode is a pitiful mess. – Womble Nov 23 '16 at 0:24

+270

SourceKitService crashes on my system as soon as I type

extension foo {

I'm using Xcode 6 beta 6 and it does not matter if I type it into an empty file or add it to an existing one. As soon as the source contains one extension block, it will crash. This happens even on newly created projects.

My "solution" is to avoid extension in the sources I'm currently working on. I comment out the end of a class block and the beginning of the extension block. As soon as I have finished my work on the class, I comment them in again:

class MyClass {

    [... my stuff ...]

//}
//
//extension MyClass {

}

You just saved my day. Already filed a bug report. – HighFlyingFantasy Aug 21 '14 at 16:53

Just a note - extensions did not do this in beta 5. It's a new beta6 "feature". – Gene De Lisa Aug 21 '14 at 17:19

Any other workaround because there are tons of extensions in my project. Can't work with this Xcode now. – Bagusflyer Aug 27 '14 at 1:12

This this this so much this. I've discovered that's what is biting me in my most recent projects. Filing a bug report now. – Ben Kreeger Aug 27 '14 at 2:32

Also a huge issue for me. I've taken to just moving extensions to their own file, writing the code in the class, them copy-pasting to the extension. How this snuck through is a little baffling. – Andrew Monshizadeh Aug 27 '14 at 13:23

+90

It started happening on my spritekit project after inserting the touchesMoved-function. This function uses forced unwrapping, which seems to cause the problem:

override func touchesMoved(touches: NSSet!, withEvent event: UIEvent!)

After removing the exclamation marks and thus stopping forced unwrapping, the SourceKitService stopped crashing.

Hope this helps!

Worked for me! Thanks a lot (hope they will fix it!) – Napolux Jul 5 '14 at 13:06

+90

I found a solution on Apple's Developer Forums (which requires login, so I'll explain it here too).

TLDR: Don't import a @protocol in your Objective-C to Swift bridging header that is named the same as an @interface. For example, the Facebook SDK has both a protocol and an interface named "FBGraphObject".

Here's the forum post:

Adding Facebook SDK causes SourceKitService to crash. If you want to use beta 3 and you need Facebook SDK, one work around that I found and is working for me is refactoring Facebook SDK's @protocol FBGraphObject and renaming it to something like @protocol FBGraphObjectProtocol as an @interface FBGraphObject also exists and apparently SourceKit doesn't like it.

It sure is a temporary solution just to keep you functional and you'll have to use Cocoapods or otherwise build Facebook SDK yourself rather than using the framework library.

For the time being, you'll need to make sure you don't have conflicting @protocol and @interface declarations and that includes 3rd party libraries you may be using.

This cost me today, hope it helps!


Posted by e.parto on July 10, 2014

Thanks a lot. It resoled my problem. – Viktor Radchenko Jul 16 '14 at 6:59

This bug can surface if you are using Jon Sterling's Pattern for Lightweight Immutability (jonmsterling.com/posts/…), since it advises protocols that share a name with their implementation. Renaming the protocols solved the problem for me with no ill effects. – erikprice Jul 19 '14 at 0:46

PERFECT!!! Problems also with NimbusKit – Vaseltior Jul 22 '14 at 15:25

This has been solved for me with Facebook SDK 3.17.1 – KVISH Aug 24 '14 at 0:24

這為我修好了!謝謝

+80

Use other name than Swift for the project. "Swift" is reserved.

I also receive this warning, but my project's name does not include the word Swift at all, so this is not "the" solution, just maybe "a" solution. And no, I haven't figured out what the issue is with mine. – Andrew Monshizadeh Jun 4 '14 at 14:24

@AndrewMonshizadeh同樣的問題,沒有對Swift的引用,但在我收到此錯誤之前,我幾乎不能輸入一兩個字符。 - BytesGuy 2014年6月4日17:22

當我嘗試在UIView的子類上使用代碼完成時,進一步的調查使我確定我收到了SourceKitService Terminated錯誤。 - Andrew Monshizadeh 2014年6月7日14:51

This is not the cause of the issue. I have no idea why this is upvoted. – Santa Claus Jun 18 '14 at 18:40

NRitH,我在使用Xcode 6 beta 1時遇到了這個問題,更改項目是一個對我有用的修復。可能有很多錯誤會觸發此錯誤。您可能正在使用更新版本的Xcode,他們可能已修復該錯誤。 - Marius Fanu 2014年7月2日11:09

+80

I had this problem every few seconds in Xcode 6 Beta 3, and it continued even in completely new projects. I changed the Deployment Target from 8.0 to 7.1 and it has stopped.

+50

Is your project named Swift? With seeing that message, build would be failed too(<unknown>:0: error: module name "Swift" is reserved for the standard library). Try using another project name such as SwiftTest. It would work.

+30

In order to fix this you may have some weird issue with your Swift code. For instance having multiple defintions of IBOutlets because you were in the middle of copying and pasting. usually it is just a syntax error that couldnt be handled.

我在Xcode項目模板中看到了未修改代碼的問題,所以我認為這不是Swift代碼的問題。 - ThomasW 2014年6月3日7:03

它可能由多個具有相同名稱的IBOutlet引起。 - 托尼6月3日在19:50

+30

I found that by explicitly (statically) typing the variable types, rather than inferring them, solved the issue for me.

這應該更多。 - Departamento B 16年5月5日16:49

+30

Quit Xcode if it's open. Then from Terminal run:

defaults delete com.apple.dt.Xcode

This will restore Xcode to the default settings. Open Xcode and everything should work again.

+20

For me (xcode 6.1) reason was that I forgot to adopt my subclass to protocol.

For example this is wrong:

protocol SomeProtocol { ... }
class A :NSObject, SomeProtocol {
...
}
class B : A {
...
}

and this is ok:

protocol SomeProtocol { ... }
class A : NSObject, SomeProtocol {
...
}
class B : A, SomeProtocol {
...
}

與遺忘的協議有同樣的問題。感謝您的意見。似乎xcode的發布版仍然像beta =) - John Kakon 2014年10月28日9:50

謝謝!我一直在瘋狂。您的解決方案解決了我的問 我希望這將被修復,似乎很奇怪,必須在每個子類上添加協議.. - Alvin 11年11月19日在20:58

+10

A program consisting only of these two lines (possibly wrong in terms of Swift syntax) is enough to cause the "SourceKitService Terminated" error here:

var x = 42
println("Hello", x)

Using let instead of var makes the editor behave normally again. Xcode version 6.0 (6A215l)

但那個println沒有意義...... - Lyndsey Scott 2014年7月16日12:21

我通常懷疑當Xcode無法處理某種語法錯誤時會出現這個錯誤 - 在實際代碼中或在構建時(在項目名稱中有swift的例子) - Lyndsey Scott 2014年7月16日12: 22

我說錯誤可能是由語法錯誤引起的,因為你的代碼有明確的語法錯誤,這符合我的理論。 - Lyndsey Scott 2014年7月18日0:13

“SourceKitService Terminated”作為對語法錯誤的響應毫無意義。這是我指出的錯誤。這是有問題的bug。 - 亞歷山大於2014年7月19日14:06

是。這就是“bug”這個詞的意思。這個錯誤似乎是由語法錯誤引發的。希望Apple能盡快修復它。 - Lyndsey Scott 2014年7月19日16:05

+10

Got same issue today, the thing was with println, I just tried the old NSLog style to print a value:

// something like this
println("value = %@", valueObj)

The way how we should compose strings in swift has evolved from printf style to inline style, so now you embed your values right into the format string like this:

"Here goes (YOUR_VARIABLE)"

So, for the example above the solution is:

println("value =(valueObj)")

嘿,@ downwoter,這個答案有什麼問題?對我來說似乎很好。我知道我們仍然可以使用NSLog和Swift,但println是自Swift以來的方法。而這個答案直接與問題有關,所描述的行崩潰了SourceKit服務。 - MANIAK_dobrii 2014年6月23日7:10

我有一個類似的問題與println()試圖打印一個未命名的元組 - thisispete 2014年7月5日在20:24

+10

I had same issue with Xcode6 beta 3 for a project created in beta 2.

It was because of new breaking changes in swift language i.e. array declaration syntax.

Check for the effected code due to breaking changes in beta 3.

http://adcdownload.apple.com//Developer_Tools/xcode_6_beta_3_lpw27r/xcode_6_beta_3_release_notes__.pdf

One of the example in my case was:

I had to change:

var tabBarController : UITabBarController = self.window?.rootViewController as UITabBarController;

to

var tabBarController : UITabBarController = self.window!.rootViewController as UITabBarController

Conclusion: Looks like if there is an error in source code, in some conditions this error is produced by Xcode.

Solution till the bug is fixed: Check for the error manually :)

Goodluck!

+10

The solution for me happened to be changing the simulator. I was using iPhone 5S for my simulator and when I switched it to iPhone 5, everything worked perfectly. Hopefully a future version will fix it altogether.

我發現iPhone 5模擬器永遠是最好的選擇,每隔一個崩潰 - Daniel Galasko 2014年10月20日18:24

@DanielGalasko很有意思。我通常使用iPhone 5S,它對我來說非常穩定。 - Fomentia 2014年11月13日18:59

如果你正在使用Xcode 6.1那麼這已經解決了我的理解:) - Daniel Galasko 2014年11月14日5:30

我撤回我的陳述它仍然破碎,5絕對是唯一的工作模擬器 - Daniel Galasko 2014年11月20日10:44

+10

I found that removing derived data from terminal resolves the issue until next crash. :S

It is located at: /Users/{User name}/Library/Developer/Xcode/DerivedData/{Project Name}-{Random char sequence}

I hope this helps.

+10

I think I figured out one (as there are probably many) of the reasons this occurs.

In my case, I was importing Objective-C files through the Bridging Header that had one of the following true:

  1. The implementation file (.m) for the Objective-C import, did not have the app target properly set.
  2. The Objective-C file only had a header (.h) file and NOT an implementation (.m) file. (Again, I think this is part of the "no proper app target" set, as you can only set targets in the .m files and not the .h files)

Fixing the app targets on the Objective-C files OR removing the import of those file(s) in the Bridging Header all together seems to fix the issue.

FYI - If you need to set the target of Header (.h) files that have no Implementation (.m) file, you can follow these simple steps: Can't change target membership visibility in Xcode 4.5

+10

Just to add one more potential solution here, I had accidentally named a class var the same name as it's type:

class var Settings:Settings {
        get { return classVarWorkAround.settings }
    }

This will crash SourceKit FOR SURE. Stupid syntax error, but in case anyone else makes the same mistake.

Edit: also according to @Portland Runner:

Similarly, If you set the return type to the func name you'll get the error.

func foo() ->foo{}

同樣,如果將返回類型設置為func名稱,則會收到錯誤。func foo() - > foo {}(隨意將其添加到您的答案中) - Portland Runner 2015年4月1日22:03

0

When this error starts popping up, just comment out the last/recent piece of code you wrote and wait for a while. The syntax highlighting should reappear. This is how I work around the problem.

    func someFunc() -> (Int?, Int?, Int?) {
     var retVal1:Int? = nil
     var retVal2:Int? = nil
     var retVal3:Int? = nil

     //some other code

     //commenting out the line below helped me
     //(retVal1, retVal2, retVal3)
     return (retVal1, retVal2, retVal3)
    }

無論你做什麼,系統都會重新啟動。您不必註釋掉該行,它仍然會很快再次開始運行。當然還有崩潰。 - Maury Markowitz於2014年11月5日15:58

0

Reported to Apple (#17266321) :

Details:

Summary: If we try to print a dictionary with value as an array a pop-up keeps on popping saying -"SourceKit terminated. Editor functionality temporaly limited". Xcode Freezes and looses context recognition causing text to be blackened.

Steps to Reproduce: 1. Create an array as - "var iOSHistoryArray = ["iOS6","iOS7","iOS8",]"

  1. Create an dictionary as -"var MacOSYosemiteFeatures:Dictionary = ["Device":iOSHistoryArray]".

  2. Print the dictionary as - "println("Dictionary containing Array value : %@ ",MacOSYosemiteFeatures)" (<<- Culprit-->>)

  3. The step 3 causes the issue commenting which makes the Xcode functional again.

Expected Results: Xcode should function normally.

Actual Results: Xcode becomes nonfunctional, looses context recognition (All font is lost and all text becomes plain black), whole Xcode becomes Inactive.

Version: Version 6.0 (6A215l)

0

Try It:

There is a bug in the Swift compiler / indexer. Some line or lines in your code is giving it difficulty. You will have to edit your code with some other text editor to comment out the offending line(s) before you will be able to open that project with Xcode. If you have no clue what the problem is, comment out all your code. Once you have the project open, you can start bringing back code little by little until the rise in CPU activity tells you that you've found the problem.

複製自:stackoverflow.com/a/24442837/1402846 - Pang Aug 3 '14 at 11:20

@Pang如果答案是正確有效的,那麼問題可能是重複的,所以你應該投票或標記關閉它們 - 在這種情況下,這絕對是開放的 - Mark 8年8月8日在20:21

0

Problem:

  • If there is an error in source code, the "SourceKitService Terminated" pop up may appear and code highlighting stops working. It may or may not happen, when it does its under multiple different conditions.

My case: Installed beta 3, OSX only project, one file detected the "half-closed range operator has been changed from .. to ..<" error. The pop up starts appearing and code highlighting starts failing.

Solution:

  • Fix error detected by Xcode
  • Change to a different .swift in Navigator, come back to the original
  • Syntax highlighting reappears and "SourceKitService Terminated" pop up is gone
0

In xcode, go to your menu bar >> window >> devices (shift+cmd+2) a new window will pop up, and on the bottom left, add a new simulator, specifically one running on iOS 8.0 to the existing list edit: you might need to restart xcode

refrence:http://www.reddit.com/r/swift/comments/2bznfo/error_running_playground_unable_to_find_suitable/

0

In my case I had imported missing files in bridged header. After I deleted wrong imports the error notification gone.

0

I had the same error with the nested Objective-C++ project that now includes Framework with Swift code. In order to fix this issue I had to explicitly build the framework. Once I did that issue is gone, and doesn't come back ;)

0

Still happening with xcode 6 Version 6.0 (6A313)

  • Create a new project
  • Add a Framework & Library
  • Select cocoa touch framework
  • Add a Swift file
  • Add a class to the swift file

Crashes

ps: brand new mac mini, no previous xcode installs, nothing exotic. Just a beta product I suppose.

0

Xcode 6.1 Beta 3:

As soon as you define a non-private type alias (e.g. typealias Foo = Int) in one Swift file an type the letter c in another file the SourceKitService crashes.

Solution is either resign from using type aliases, wait for the next beta release or wrap your type aliases in class definitions:

public class DummyClass {
    public typealias Foo = String
}

and use it like this:

var myVar:DummyClass.Foo?
0

Changing the deployment target to iOS 8.0 worked for me. I know someone said moving it to <=7.1 worked, but this problem seems to come in from multiple sources, so this alternative may work.

828
votes
answers
19 views
+10

Xcode “Device Locked” When iPhone is unlocked

When I tried to build and run, Xcode said my device was locked. I looked at my iPhone, and it's not locked at all. How do I fix this?

up vote 116 down vote accepted favorite
沙发
+1160
+50

Did you by chance not "trust" the device? This will prevent it from communicating with xcode even if the device is unlocked.

Update here's a support doc from Apple: http://support.apple.com/en-us/HT5868

我不確定你的“信任”是什麼意思......我如何實現這一點? - Faisal Syed 2014年11月6日23:59

拔下設備,關閉xcode,然後打開xcode並插入設備。當您將其插入(解鎖後)時,系統會提示您“信任”計算機(在iOS設備中)。我的猜測是你可能不小心點擊了“不信任”,因此設備將拒絕連接到計算機。 - tehprofessor 2014年11月7日0:01

我已經通過蘋果支持頁面鏈接更新了答案。 - tehprofessor 2014年11月7日0:02

@NicolasMiari我已經有其他通知顯示,同時我插入手機導致它消失,或意外地忽略我的Mac上的提示...同樣,如果你使用移動配置器有可能它導致一些奇怪的問題,因為設備可以配置為僅響應一台機器。也許第一次插入時,握手搞砸了? - tehprofessor 18年6月7日21:13

啊......另一個“搖擺開關”解決方案。 - Zmart 18年9月19日16:09

+4010

My phone was set to "trust" the Mac, and I still ran into this error with Xcode 6.1.1.

This worked for me:

  • unplug device
  • quit xcode
  • open xcode
  • plug in device
  • build/run

不幸的是,這往往是許多奇怪的Xcode問題的解決方案。 - Jarsen 2015年12月20日3:58

每次退出Xcode都是浪費。 - Nik Kov 18年7月27日10:06

這應該是正確的答案。 - Kaizer Sozay於18年11月11日9:04

“你試過把它關掉再打開嗎?!” - 每次都有效! - 邁克詹姆斯1月14日15:12

+960

I recently ran into this issue with XCode 8 just after updating my device from iOS 9 to 10. The exact error I received was:Development cannot be enabled while your device is locked. Please unlock your device and reattach. I received this error even when my phone was unlocked, and after unplugging and re-plugging in the device.

As is mentioned in several answers, the device is locked message is actually referring to the device not trusting the MacBook. In my case, I think my phone defaulted to not trusting my computer after updating to iOS 10. Here are the steps that worked for me to reset the settings (this is the same process that is mentioned in the Apple support page in tehprofessors' answer):

  1. Disconnect your device from your MacBook and close Xcode.
  2. On your device go to Settings > General > Reset, then tap Reset Location & Privacy
  3. Plug your device back into your computer, and on the device you will be prompted to trust the computer. Tap trust.
  4. Now reopen Xcode and rebuild the project.
  5. The device locked error should disappear.

是的,不幸的是,這只適用於iOS 10上的Xcode 8 :( - Bishal Ghimire 2016年10月25日3:41

@BishalGhimire是的,這絕對不是理想的。我實際上只是需要再次重置,因為XCode開始再次給我設備鎖定消息,而不會對我的任何iPhone設置或XCode的設置進行任何明顯的更改。我的計算機信任設置正在重置,但我不確定何時何地。 - 鐵約翰邦尼2016年10月25日19:16

你應該等待一段時間來處理符號文件--Hamed.Ghadirian 2016年11月20日7:22

嗯......這修復了“設備鎖定”錯誤......但已將其替換為“無法保存配對記錄”。錯誤... - kris 2016年12月20日4:22

在iOS 11軟件更新設備/ Xcode 9 - Ben Oct 18 '17 10:22之後,這對我有用

+510

From the Window Menu in top bar of Xcode, select Devices and Simulators.

(or Press SHIFT + COMMAND + 2)

Then select your device, right click and select Unpair.
Once you do this Trust or Don't trust will appear on your device.
Trust the device again and it will begin preparing it for Development.
Wait for Xcode to pair device for development and then you are good to go!

問題通常不是等待xcode準備iPhone調試:)這工作 - Abdelrahman Ellithy 4月24日'18在4:02

這對我有用。謝謝 - 傑文查爾斯1月1日21:06

工作就像一個魅力,謝謝 - Anonymous-E 4月10日7:25

有關unpair的詳細說明,請參閱forums.developer.apple.com/thread/52048 - Atara 5月15日13:36

+390

I ran in to the same issue even though i selected "Trust this computer" option first time.

This worked for me

  1. Lock the device
  2. Remove cable from device.
  3. Unlock the device
  4. Connect again to Mac

Abhi Beckert的上述答案之前對我有用,現在這對我有用。我花了大量的時間在Apple的無能的開發者周圍跳舞。 - 公關於2017年6月16日9:44

那對你來說是蘋果!在IB的屬性檢查器中更改某些值將使您的xcode更快。大聲笑。 - Itzdsp 17年6月16日15:59

這解決了我的問題! - 鄭浩2017年10月28日凌晨2點26分

+210

2018

The fastest way for now i found is:

1) Go to Window -> devices (changed the hotkey in xcode to CMD+P for me)
2) Press unpair on the device. enter image description here
3) Press trust in iPhone.
4) Build again or Run without building (Ctrl+CMD+R)

+190

For anyone who need a logical answer..

  1. Go to Window -> Devices & Simulators. Right click on your device & unpair it.
  2. Disconnect from cable & reconnect.
  3. Wait for it & let Xcode detect you device.
  4. Run the project.
  5. Make sure you TRUST on your iOS device and enter any passcode.

這很有效。最初配對時,請確保您的設備已解鎖。如果沒有,請按照這些說明進行修復。 - Wizkid 18年5月14日15:29

+160

Rebooted my iPhone, and that fixed it for me.

I tried every answer on this page (7 at the time, though 2 are duplicates) and they were all unsuccessful for getting rid of this Xcode error for me.

這節省了我的一天!謝謝! - 方明19年10月19日凌晨1點05分

這是節省我大量時間的最佳答案。謝謝 - Gaurav 17年11月14日11:26

對我沒有幫助。只有設置不受信任和信任再次幫助。 - Nik Kov 18年2月17日10:48

你不需要每次重啟或重啟。檢查我的答案:stackoverflow.com/a/50023756/9623144 - Amber K Jun 20 '18 at 3:43

每次重啟手機都是浪費時間。 - Nik Kov 18年7月27日10:01

+110

For those who has this issue in Xcode 9: Simply restarting Xcode should solve the problem.

這是正確的,尤其是在Xcode 9中進行wifi調試的情況下。 - Ben Lachman於17年11月12日0:02

+100

A simple solution:

  1. First, unplug your device.

  2. Now, unlock your device and plug it in again. Be sure that the device is unlocked.

  3. Now run the Xcode project by selecting the device as target.

我也一樣。另外,我能夠調試無線。 - Mykhailo Lysenko 17年12月23日12:29

+80

When you plug in your iPhone, it will ask you to trust the computer. If you already trust and unlocked but still said your device was locked (bug). Just unplug and plug again then it will work

+70

This happens at times while using Xcode 9.

Screenshot

There are multiple solution to this as mentioned below :

Note : Make sure that your device is not locked when Xcode is trying to install app.

Solution 1 :

i. Disconnect device and connect again

Solution 2 :

i. Restart you device

Solution 3 :

i. Disconnect device

ii. Quit Xcode (Shortcut key : cmd + Q)

iii. Open your project

iv. Clean project (Shortcut key : cmd + shift + K)

v. Now connect device

vi. Run your project

For me Solution 3 worked perfectly

解決方案#3對我有用。 - capikaw 18年4月23日20:37

+60

These steps worked for me in iOS 10.

  1. Remove the cable from device.
  2. Plug in the device.
  3. Clean and build the Xcode project.
+50

Recently I have met the Xcode shows "development cannot be enabled while your device is locked, Please unlock your device and reattach. (0xE80000E2).

If your iOS device is already unlocked and connected to mac and still get the error from Xcode 8.1 after upgrading to iOS 10.1.1, then the mac is not trusted by the device.

To fix it, first disconnect device to mac and then go to iOS settings app, and open general->reset->Reset Location & Privacy.

Then connect device to mac and when prompted, set select trust the mac.

Then wait the processing symbol files within your device and mac. After it finished, you can run the project to your device. It will be working.

+40

Solution: Switch target device to some other (e.g. Generic iOS Device),

enter image description here

then unlock you physical device and switch back to it again.

+40

This issue is not about "Trust" or not. It's a bug in Xcode.

Just follow these steps.

When Xcode is running and your device is connected:

  1. Lock your device.
  2. Unplug your device from Mac.
  3. Unlock your device.
  4. Plug your device back to Mac.

仍然沒有工作( - Nik Kov 18年7月27日在10:02

+40

There is a simple way to resolve that. At least it works for me. In your iPhone Device Go to Setting > Developer > click in “Clear Trusted Computer” Type the passcode required And done!!!

The simplest way that I found.

很好,謝謝! - 肖恩18年8月30日18:18

非常感謝為我工作;) - 皮埃爾18年9月24日在3:35

+30

I run into this problem quite often (at least like 5 times a week). Almost every time this happens, a Xcode restart fixes it. But this time nothing seemed to work including:

  • Restarting Xcode;
  • Unplugging and re-plugging the iPhone;
  • Cleaning the project (cmd+shift+k);
  • Cleaning derived data (cmd+option+shift+k)

Done dozens of times in all sorts of different orders.

What fixed the issue for me this time was simply:

? Rebooting the Mac.

這個對我有用,雖然,我也殺了Xcode。 - Yash Bedi 4月29日9:59

+20

Generally just unplugging/replugging seems to work for me. But today it didn't and something else seems to have worked: I have enabled network debugging on the device in question and it almost looked like it remembered an old network "lock" setting, while not seeing that the device was actually connected via USB. After (temporarily) de-selecting "Connect via Network" and replugging, it got things working again.

+20

there are two solution worked for me. 1) disconnect your device from the mac and reattach it. 2) disconnect your device from the mac and restart it and then connect it with mac it'll work

+10

Lots of answers, but the one that worked for me (El Capitan, Xcode 8.2) was to close iTunes. If that has a connection to the IOS device then although Xcode can load the app components it will still fail to run it.

+10

I found that by shutting down a Console and a running Simulator allowed XCode to see my iPhone again. I'd make sure other related programs aren't running if you don't need them.

+10

This can also happen due to pending update on your device. This also means you need to update your phone, connect to the MacBook (trust it if needed). This how I found my problem and solution.

我有同樣的問題(更新在設備上等待)但我沒有時間更新它。Asfand Shabbir的回答奏效了。(如果讀者沒有時間更新) - 可以Poyrazoğlu18年5月6日在10:55

0

sometimes your device stops trusting your PC for no reseaon. go to your settings then general > reset > reset location and privacy. and replug your device to your PC again and press "trust this device" prompt that shows up in your phone.

0

Another fix to this problem is to connect your iPhone with your Xcode open while your iPhone is in the homescreen, not in lockscreen or with an app opened.

0

All the previous solutions didn't work.

Finlay, changing the iPhone's cable solved the problem.

0

On your device (iPhone/iPad) goto: Settings -> Developer -> Clear Trusted Computers worked for me.

這就是我必須要做的就是“相信這台電腦?” 當我連接到我的電腦時出現提示--Nunchucks 18年6月26日20:31

0

I had to re-add device to xcode.

In XCode open Devices and Simulators (CMD+Shift+2), in left list press + button and re-add the same device.

0

Check the "Low Power Mode" in disabled. In my case I just disable this check and the deploy works immediately,

0

One possibility worth checking, if none of these other solutions work, is that there is no space left on the device. Xcode will not give you a helpful "device full" error to tell you that your device has no storage space left, but it will also not be able to deploy an app build to a device whose storage is full. The only solution in that situation is to delete media or other apps/data to free up enough space.

917
votes
answers
13 views
+10

How to control the line spacing in UILabel

Is it possible to reduce the gap between text when put in multiple lines in a UILabel? We can set the frame, font size and # of lines. I want to reduce the gap between the two lines in that label.

up vote 236 down vote accepted favorite
沙发
+2360
+50

I thought about adding something new to this answer, so I don't feel as bad... Here is a Swift answer:

import Cocoa

let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = 40

let attrString = NSMutableAttributedString(string: "Swift Answer")
attrString.addAttribute(.paragraphStyle, value:paragraphStyle, range:NSMakeRange(0, attrString.length))

var tableViewCell = NSTableCellView()
tableViewCell.textField.attributedStringValue = attrString

"Short answer: you can't. To change the spacing between lines of text, you will have to subclass UILabel and roll your own drawTextInRect, or create multiple labels."

See: Set UILabel line spacing


This is a really old answer, and other have already addded the new and better way to handle this.. Please see the up to date answers provided below.

從iOS 6.0開始,您可以通過NSAttributedString控制它(在Xcode的界面構建器中也可以在UILable的屬性中使用)。 - ıɾuǝʞ12年12月18日9:21

有趣的是,就我所知,你可以在行之間添加額外的間距,但在使用NSAttributedString時不能通過NSParagraphStyle減少它。(我可能需要對其他可修改屬性進行更多測試,但lineSpacing屬性只允許你增加它。) - livingtech 2013年9月12日21:28

看到我的回答,看看使用NSAttributedString的方法 - d.ennis 2013年10月8日21:21

@livingtech這真氣,我相信你是對的。你找到了解決辦法嗎? - Dom Vinyard 2014年11月7日14:04

只是為了澄清這個帖子中的內容。如果你想縮小行間距,將行高設置為1.0,然後將setLineHeightMultiple設置為較低的值<1.0,如:[paragraphStyle setLineHeightMultiple:0.8]或paragraphStyle.lineHeightMultiple = 0.8 - virsunen 2016年7月13日2:25

+3840

In Xcode 6 you can do this in the storyboard:

enter image description here

這應該有更多的讚成! - Nic Hubbard於2014年12月5日3:23

@PaperThick在6.1.1中有同樣的問題。它“哈利震動”幾分鐘。不知道如何解決它:) Xcode Shaking - Anton Gaenko 2015年1月16日12:15

有沒有辦法以這種方式設置自定義字體?我似乎無法改變任何其他字體的helvetica neue。 - Marcos Curvello 2015年2月25日1:57

如果你啟用'Attributed',然後打開文件作為源代碼,你可以手動編輯'lineHeightMultiple',因此繞過Harlem Shake bug - ED-209 2015年6月4日14:25

@azdev對於那些仍然在看這個的人,我在Xcode 7.3中得到了更長的震撼,但我認為這是第一個沒有出現問題的版本 - LulzCow 16年4月13日在20:07

+1000

Starting from iOS 6 you can set an attributed string to the UILabel. Check the following :

NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:label.text];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.lineSpacing = spacing;
[attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, label.text.length)];

label.attributedText = attributedString;

attributionString必須是NSMutableAttributedString(NOT NSAttributedString) - Mike S 2014年9月25日17:01

第一行代碼應該是NSMutableAttributedString * attributedString = [NSMutableAttributedString alloc] initWithString:@“sample text”]; - 艾倫12年12月12日15:11

NSMutableParagraphStyle的lineSpacing屬性從不為負數,因此使用此方法無法減小行高。要回答這個問題,你必須使用另一個屬性,請參閱@ d.ennis回答。 - Theo 2015年5月3日10:28

+790

The solutions stated here didn't work for me. I found a slightly different way to do it with the iOS 6 NSAttributeString:

myLabel.numberOfLines = 0; 
NSString* string = @"String with line one. 
 Line two. 
 Line three.";
NSMutableParagraphStyle *style  = [[NSMutableParagraphStyle alloc] init];
style.minimumLineHeight = 30.f;
style.maximumLineHeight = 30.f;
NSDictionary *attributtes = @{NSParagraphStyleAttributeName : style,};
myLabel.attributedText = [[NSAttributedString alloc] initWithString:string
                                                         attributes:attributtes];   
[myLabel sizeToFit];

行高與字體大小有關。行間距就是行間距。您可以通過設置最小/最大行高來解決問題,但這只是因為您使用的當前字體大小不大於行高邊界。根據文檔:“......超過此高度的字形和圖形將與相鄰的線重疊......雖然此限制適用於線條本身,但線間距會在相鄰線條之間增加額外的空間。” - Ari Braginsky 2013年10月17日1:11

+1,如果你想減少線之間的間距,這就是你想要做的。實際行間距很可能默認為0,這就是為什麼人們報告你只能增加它。間距太大的問題來自於線高太大,這就是為什麼這將在99%的時間內完成工作。 - lawicko 2015年3月10日11:11

這是我能找到的唯一一個使用Photoshop,Sketch,CSS等設計應用程序常用的行高度值(而不是比率)的答案.-- Albert Bori 17年1月24日19:16

+310

I've made this simple extension that works very well for me:

extension UILabel {
    func setLineHeight(lineHeight: CGFloat) {
        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.lineSpacing = 1.0
        paragraphStyle.lineHeightMultiple = lineHeight
        paragraphStyle.alignment = self.textAlignment

        let attrString = NSMutableAttributedString()
        if (self.attributedText != nil) {
            attrString.append( self.attributedText!)
        } else {
            attrString.append( NSMutableAttributedString(string: self.text!))
            attrString.addAttribute(NSAttributedStringKey.font, value: self.font, range: NSMakeRange(0, attrString.length))
        }
        attrString.addAttribute(NSAttributedStringKey.paragraphStyle, value:paragraphStyle, range:NSMakeRange(0, attrString.length))
        self.attributedText = attrString
    }
}

Copy this in a file, so then you can use it like this

myLabel.setLineHeight(0.7)

記住如果你在使用Storyboard這個標籤時這樣做,那麼一定要把你的標籤線設置為0 - Honey 2016年8月1日3:10

你為什麼不直接設置lineSpacing而忘記設置lineHeightMultiple? - 蜂蜜2016年8月1日3:27

因為減少線高的關鍵是'lineHeightMultiple',沒有lineSpacing - Agustin Meriles 2016年8月1日3:33

假設你想要你的行高為1.4,為什麼你不能只寫.lineSpacing = 1.4而忘記了所有關於.lineHeightMultiple ... - Honey 2016年8月1日在3:40

你試過嗎?它有用嗎? - 奧古斯丁梅里斯2016年8月1日3:42

+230

From Interface Builder (Storyboard/XIB):

enter image description here

Programmatically:

SWift 4

Using label extension

extension UILabel {

    // Pass value for any one of both parameters and see result
    func setLineSpacing(lineSpacing: CGFloat = 0.0, lineHeightMultiple: CGFloat = 0.0) {

        guard let labelText = self.text else { return }

        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.lineSpacing = lineSpacing
        paragraphStyle.lineHeightMultiple = lineHeightMultiple

        let attributedString:NSMutableAttributedString
        if let labelattributedText = self.attributedText {
            attributedString = NSMutableAttributedString(attributedString: labelattributedText)
        } else {
            attributedString = NSMutableAttributedString(string: labelText)
        }

        // Line spacing attribute
        attributedString.addAttribute(NSAttributedStringKey.paragraphStyle, value:paragraphStyle, range:NSMakeRange(0, attributedString.length))

        self.attributedText = attributedString
    }
}

Now call extension function

let label = UILabel()
let stringValue = "How to
control
the
line spacing
in UILabel"

// Pass value for any one argument - lineSpacing or lineHeightMultiple
label.setLineSpacing(lineSpacing: 2.0) .  // try values 1.0 to 5.0

// or try lineHeightMultiple
//label.setLineSpacing(lineHeightMultiple = 2.0) // try values 0.5 to 2.0

Or using label instance (Just copy & execute this code to see result)

let label = UILabel()
let stringValue = "How to
control
the
line spacing
in UILabel"
let attrString = NSMutableAttributedString(string: stringValue)
var style = NSMutableParagraphStyle()
style.lineSpacing = 24 // change line spacing between paragraph like 36 or 48
style.minimumLineHeight = 20 // change line spacing between each line like 30 or 40

// Line spacing attribute
attrString.addAttribute(NSAttributedStringKey.paragraphStyle, value: style, range: NSRange(location: 0, length: stringValue.characters.count))

// Character spacing attribute
attrString.addAttribute(NSAttributedStringKey.kern, value: 2, range: NSMakeRange(0, attrString.length))

label.attributedText = attrString

Swift 3

let label = UILabel()
let stringValue = "How to
control
the
line spacing
in UILabel"
let attrString = NSMutableAttributedString(string: stringValue)
var style = NSMutableParagraphStyle()
style.lineSpacing = 24 // change line spacing between paragraph like 36 or 48
style.minimumLineHeight = 20 // change line spacing between each line like 30 or 40
attrString.addAttribute(NSParagraphStyleAttributeName, value: style, range: NSRange(location: 0, length: stringValue.characters.count))
label.attributedText = attrString

應該接受答案。 - 評論時間70年01月01日20:02

添加“paragraphStyle.alignment = self.textAlignment”行以保持原始對齊。否則,文本將保持對齊。 - Nithin Michael 4月29日9:57

+190

There's an alternative answer now in iOS 6, which is to set attributedText on the label, using an NSAttributedString with the appropriate paragraph styles. See this stack overflow answer for details on line height with NSAttributedString:

Core Text - NSAttributedString line height done right?

+160

Here is a class that subclass UILabel to have line-height property : https://github.com/LemonCake/MSLabel

這對我有用,謝謝。我也試過使用MTLabel,但這個更好。 - wzbozon 2013年1月10日16:20

有誰知道MSLabel是否支持''字符? - achi 2013年7月10日2:02

根據文檔,換行符被忽略 - Zee Dec 14 '14 at 11:11

+80

In Swift and as a function, inspired by DarkDust

// Usage: setTextWithLineSpacing(myEpicUILabel,text:"Hello",lineSpacing:20)
func setTextWithLineSpacing(label:UILabel,text:String,lineSpacing:CGFloat)
{
    let paragraphStyle = NSMutableParagraphStyle()
    paragraphStyle.lineSpacing = lineSpacing

    let attrString = NSMutableAttributedString(string: text)
    attrString.addAttribute(NSAttributedString.Key.paragraphStyle, value:paragraphStyle, range:NSMakeRange(0, attrString.length))

    label.attributedText = attrString
}
+60

According @Mike 's Answer, reducing the lineHeightMultiple is the key point. Example below, it work well for me:

    NSString* text = label.text;
    CGFloat textWidth = [text sizeWithAttributes:@{NSFontAttributeName: label.font}].width;
    if (textWidth > label.frame.size.width) {
        NSMutableParagraphStyle *paragraph = [[NSMutableParagraphStyle alloc] init];
        paragraph.alignment = NSTextAlignmentCenter;
        paragraph.lineSpacing = 1.0f;
        paragraph.lineHeightMultiple = 0.75;     // Reduce this value !!!
        NSMutableAttributedString* attrText = [[NSMutableAttributedString alloc] initWithString:text];
        [attrText addAttribute:NSParagraphStyleAttributeName value:paragraph range:NSMakeRange(0, text.length)];
        label.attributedText = attrText;
    }
+50

SWIFT 3 useful extension for set space between lines more easily :)

extension UILabel
{
    func setLineHeight(lineHeight: CGFloat)
    {
        let text = self.text
        if let text = text 
        {

            let attributeString = NSMutableAttributedString(string: text)
            let style = NSMutableParagraphStyle()

           style.lineSpacing = lineHeight
           attributeString.addAttribute(NSParagraphStyleAttributeName,
                                        value: style,
                                        range: NSMakeRange(0, text.characters.count))

           self.attributedText = attributeString
        }
    }
}
+30

I've found a way where you can set the real line height (not a factor) and it even renders live in Interface Builder. Just follow the instructions below. Code is written in Swift 4.


Step #1: Create a file named DesignableLabel.swift and insert the following code:

import UIKit

@IBDesignable
class DesignableLabel: UILabel {
    @IBInspectable var lineHeight: CGFloat = 20 {
        didSet {
            let paragraphStyle = NSMutableParagraphStyle()
            paragraphStyle.minimumLineHeight = lineHeight
            paragraphStyle.maximumLineHeight = lineHeight
            paragraphStyle.alignment = self.textAlignment

            let attrString = NSMutableAttributedString(string: text!)
            attrString.addAttribute(NSAttributedStringKey.font, value: font, range: NSRange(location: 0, length: attrString.length))
            attrString.addAttribute(NSAttributedStringKey.paragraphStyle, value: paragraphStyle, range: NSRange(location: 0, length: attrString.length))
            attributedText = attrString
        }
    }
}

Step #2: Place a UILabel into a Storyboard/XIB and set its class to DesignableLabel. Wait for your project to build (build must succeed!).

Specifying the class to your UILabel


Step 3: Now you should see a new property in the properties pane named "Line Height". Just set the value you like and you should see the results immediately!

Set Line Height in properties

+10

In Swift 2.0...

Add an extension:

extension UIView {
    func attributesWithLineHeight(font: String, color: UIColor, fontSize: CGFloat, kern: Double, lineHeightMultiple: CGFloat) -> [String: NSObject] {
        let titleParagraphStyle = NSMutableParagraphStyle()
        titleParagraphStyle.lineHeightMultiple = lineHeightMultiple

        let attribute = [
            NSForegroundColorAttributeName: color,
            NSKernAttributeName: kern,
            NSFontAttributeName : UIFont(name: font, size: fontSize)!,
            NSParagraphStyleAttributeName: titleParagraphStyle
        ]
        return attribute
    }
}

Now, just set your UILabel as attributedText:

self.label.attributedText = NSMutableAttributedString(string: "SwiftExample", attributes: attributesWithLineHeight("SourceSans-Regular", color: UIColor.whiteColor(), fontSize: 20, kern: 2.0, lineHeightMultiple: 0.5))    

Obviously, I added a bunch of parameters that you may not need. Play around -- feel free to rewrite the method -- I was looking for this on a bunch of different answers so figured I'd post the whole extension in case it helps someone out there... -rab

+10

Swift3 - In a UITextView or UILabel extension, add this function:

I added some code to keep the current attributed text if you are already using attributed strings with the view (instead of overwriting them).

func setLineHeight(_ lineHeight: CGFloat) {
    guard let text = self.text, let font = self.font else { return }

    let paragraphStyle = NSMutableParagraphStyle()
    paragraphStyle.lineSpacing = 1.0
    paragraphStyle.lineHeightMultiple = lineHeight
    paragraphStyle.alignment = self.textAlignment

    var attrString:NSMutableAttributedString
    if let attributed = self.attributedText {
        attrString = NSMutableAttributedString(attributedString: attributed)
    } else {
        attrString = NSMutableAttributedString(string: text)
        attrString.addAttribute(NSFontAttributeName, value: font, range: NSMakeRange(0, attrString.length))
    }
    attrString.addAttribute(NSParagraphStyleAttributeName, value:paragraphStyle, range:NSMakeRange(0, attrString.length))
    self.attributedText = attrString
}
+10

Another answer... If you're passing the string programmatically, you need to pass a attributed string instead a regular string and change it's style.(iOS10)

NSMutableAttributedString * attrString = [[NSMutableAttributedString alloc] initWithString:@"Your 
regular 
string"];
NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
[style setLineSpacing:4];
[attrString addAttribute:NSParagraphStyleAttributeName
                   value:style
                   range:NSMakeRange(0, attrString.length)];
_label.attributedText = attrString;
+10

Swift 3 extension:

    import UIKit

extension UILabel {
    func setTextWithLineSpacing(text: String, lineHeightMultiply: CGFloat = 1.3) {
        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.lineHeightMultiple = lineHeightMultiply
        paragraphStyle.alignment = .center
        let attributedString = NSMutableAttributedString(string: text)
        attributedString.addAttribute(NSParagraphStyleAttributeName, value: paragraphStyle, range: NSRange(location: 0, length: attributedString.length))
        self.attributedText = attributedString
    }
}
+10

This should help with it. You can then assign your label to this custom class within the storyboard and use it's parameters directly within the properties:

open class SpacingLabel : UILabel {

    @IBInspectable open var lineHeight:CGFloat = 1 {
        didSet {
            let paragraphStyle = NSMutableParagraphStyle()
            paragraphStyle.lineSpacing = 1.0
            paragraphStyle.lineHeightMultiple = self.lineHeight
            paragraphStyle.alignment = self.textAlignment

            let attrString = NSMutableAttributedString(string: self.text!)
            attrString.addAttribute(NSAttributedStringKey.font, value: self.font, range: NSMakeRange(0, attrString.length))
            attrString.addAttribute(NSAttributedStringKey.paragraphStyle, value:paragraphStyle, range:NSMakeRange(0, attrString.length))
            self.attributedText = attrString
        }
    } 
}

這應該有幫助。然後,您可以將標籤分配給故事板中的此自定義類,並直接在屬性中使用它的參數。 - 羅素沃里克17年11月3日14:59

請不要在評論中提供與答案相關的內容。你的答案應該是有幫助的,而不必閱讀評論 - 孤獨的神經元17年11月3日在15:23

+10

Here is a subclass of UILabel that sets lineHeightMultiple and makes sure the intrinsic height is large enough to not cut off text.

@IBDesignable
class Label: UILabel {
    override var intrinsicContentSize: CGSize {
        var size = super.intrinsicContentSize
        let padding = (1.0 - lineHeightMultiple) * font.pointSize
        size.height += padding
        return size
    }

    override var text: String? {
        didSet {
            updateAttributedText()
        }
    }

    @IBInspectable var lineHeightMultiple: CGFloat = 1.0 {
        didSet {
            updateAttributedText()
        }
    }

    private func updateAttributedText() {
        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.lineHeightMultiple = lineHeightMultiple
        attributedText = NSAttributedString(string: text ?? "", attributes: [
            .font: font,
            .paragraphStyle: paragraphStyle,
            .foregroundColor: textColor
        ])
        invalidateIntrinsicContentSize()
    }
}
+10

Swift 4 label extension. Creating NSMutableAttributedString before passing into function in case there are extra attributes required for the attributed text.

extension UILabel {

    func setLineHeightMultiple(to height: CGFloat, withAttributedText attributedText: NSMutableAttributedString) {

        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.lineSpacing = 1.0
        paragraphStyle.lineHeightMultiple = height
        paragraphStyle.alignment = textAlignment

        attributedText.addAttribute(.paragraphStyle, value: paragraphStyle, range: NSRange(location: 0, length: attributedText.length - 1))

        self.attributedText = attributedText
    }
}
0

This code worked for me (ios 7 & ios 8 for sure).

_label.numberOfLines=2;
_label.textColor=[UIColor whiteColor];

NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.lineHeightMultiple=0.5;
paragraphStyle.alignment = NSTextAlignmentCenter;
paragraphStyle.lineSpacing = 1.0;

NSDictionary *nameAttributes=@{
                               NSParagraphStyleAttributeName : paragraphStyle,
                               NSBaselineOffsetAttributeName:@2.0
                               };


NSAttributedString *string=[[NSAttributedString alloc] initWithString:@"22m
ago" attributes:nameAttributes];
_label.attributedText=string;
0

Here is my solution in swift. The subclass should work for both attributedText and text property and for characterSpacing + lineSpacing. It retains the spacing if a new string or attributedString is set.

open class UHBCustomLabel : UILabel {
    @IBInspectable open var characterSpacing:CGFloat = 1 {
        didSet {
            updateWithSpacing()
        }

    }
    @IBInspectable open var lines_spacing:CGFloat = -1 {
        didSet {
            updateWithSpacing()
        }

    }
    open override var text: String? {
        set {
            super.text = newValue
            updateWithSpacing()
        }
        get {
            return super.text
        }
    }
    open override var attributedText: NSAttributedString? {
        set {
            super.attributedText = newValue
            updateWithSpacing() 
        }
        get {
            return super.attributedText
        }
    }
    func updateWithSpacing() {
        let attributedString = self.attributedText == nil ? NSMutableAttributedString(string: self.text ?? "") : NSMutableAttributedString(attributedString: attributedText!)
        attributedString.addAttribute(NSKernAttributeName, value: self.characterSpacing, range: NSRange(location: 0, length: attributedString.length))
        if lines_spacing >= 0 {
            let paragraphStyle = NSMutableParagraphStyle()
            paragraphStyle.lineSpacing = lines_spacing
            paragraphStyle.alignment = textAlignment
            attributedString.addAttribute(NSParagraphStyleAttributeName, value:paragraphStyle, range:NSMakeRange(0, attributedString.length))
        }
        super.attributedText = attributedString
    }
}
-50

As a quick-dirty-smart-simple workaround:

For UILabels that don't have much lines you can instead use stackViews.

  1. For each line write a new label.
  2. Embed them into a StackView.(select both labels-->Editor-->Embed In -->StackView
  3. Adjust the Spacing of the StackView to your desired amount

Be sure to stack them vertically. This solution also works for custom fonts.

enter image description here

FWIW這是一個可怕但可行的解決方案。因此,我保留它。 - 蜂蜜18年12月22日11:44

我也看到iOS開發使用stackviews創建圖形的原則。Stackviews非常強大 - Honey 3月1日21:02

0
votes
answers
19 views
+10

Making OS X Installer Packages like a Pro - Xcode Developer ID ready pkg

Note: This is for OS X Installer packages only, packages for submission to the Mac App Store follow different rules.

Because of Mountain Lion's Gatekeeper I finally had to take my PackageMaker build script behind the barn and shoot it. PackageMaker was already removed from Xcode and moved into "Auxiliary Tools for Xcode", so hopefully it will be soon forgotten.

The question is how do I use pkgbuild, productbuild, and pkgutil to replace it?

0
votes
answers
27 views
+10

iOS的Sony Remote API應用程序每次嘗試運行時都會崩潰xcode

-1

我剛剛從Sony網站下載了用於IOS的Sony Remote API應用程序。但是我每次運行它時都無法在xcode 9.1上運行它。 xCode意外退出。所有其他應用程序都可以。會是什麼呢?iOS的Sony Remote API應用程序每次嘗試運行時都會崩潰xcode

沙发
0
-1

它只是不能在模擬器上工作,並在設備上正常工作。已解決

0
votes
answers
33 views
+10

Xcode 9 - Alamofire Pods。命令/ bin/sh失敗,退出代碼爲1

3
/Users/Alex/Library/Developer/Xcode/DerivedData/MyProject-ehabmnclpzlywhabrefntacibonm/Build/Intermediates.noindex/ArchiveIntermediates/Fuego/InstallationBuildProductsLocation/Applications//MyProject.app/Frameworks/Alamofire.framework: unknown error -1=ffffffffffffffff 
Command /bin/sh failed with exit code 1 

我在歸檔我的項目時遇到此問題。當我在模擬器上運行應用程序時,它工作正常,沒有上述問題。Xcode 9 - Alamofire Pods。命令/ bin/sh失敗,退出代碼爲1

此外,它可以與Xcode 8確定,但現在當我嘗試將其存檔在Xcode 9我有這個問題。但也許情況並非如此,因爲我從零開始重新安裝Mac OS,所以它可能是cocopods版本問題,我不確定。

還有兩個//這裏在上面的例子中也怪我/Applications//MyProject.app

沙发
0
2

嗯這是非常奇怪的網絡上一些搜索後,我發現,這其實是簽約的問題。

我使用Xcode生成新的分發證書,也許這會導致我的一些問題。

我做了什麼來解決我的問題。

  1. 我刪除了我的Mac和我的蘋果帳戶中的所有證書。
  2. 我刪除了所有prov配置文件以及我的Mac和我的蘋果帳戶。
  3. 我要求證書並手動將其保存在光盤上(不通過Xcode)
  4. 我重新創建證書和配置文件。手動下載並雙擊它。
  5. 之後,當我無法輸入密碼以允許簽署我的證書時,我遇到了鑰匙串問題。我使用這個link將證書表單登錄移動到系統部分。
  6. 最後我得到它的工作。
+0

我有同樣的問題,您的解決方案幫助我,謝謝 – mkul

板凳
0
5

我相信這是一個Xcode的錯誤。重新啓動您的Mac並嘗試再次構建。在構建Alamofire之前,Xcode會要求獲得訪問您的鑰匙串的權限,然後才允許它。

+0

這實際上是正確的。馬斯特羅索夫的答案有很多步驟可以遵循:P謝謝! – Glenn

+0

同意。我有類似的問題。如果我選擇模擬器,Xcode可以毫無問題地構建我的項目。在設備上,它給了我@Matrosov發佈的同樣的錯誤。重新啓動可以解決問題。 – user30646

0
votes
answers
29 views
+10

Xcode 9.1 - 文件中缺少必需體系結構x86_64

0

我正在使用庫SwipeCellKit,並且自從更新到Xcode 9.1後出現問題。我用Xcode 9.1重新編譯了這個庫,並在我的項目中重新導入了.framework。但我仍然無法使用庫中的類。我得到這樣的警告:Xcode 9.1 - 文件中缺少必需體系結構x86_64

ld: warning: ignoring file /Users/.../Frameworks/SwipeCellKit/SwipeCellKit.framework/SwipeCellKit, missing required architecture x86_64 in file /Users/.../Frameworks/SwipeCellKit/SwipeCellKit.framework/SwipeCellKit (2 slices) 

我已經試過什麼建議here和構建庫時設置Build Active Architecture OnlyNo。但它沒有幫助。我也多次清理了構建文件夾,這也解決不了問題。

+0

爲什麼你不使用Cocoa Pod添加SwipeCellKit? –

沙发
0
0

請始終使用Cocoapods爲您的項目安裝庫,它會自動管理所有依賴項。

要設置你的椰子樹項目請按照http://cocoapods.org/中提到的步驟,它會讓你的生活更容易相信我。

一旦你設置的CocoaPods成功, 再加入

pod 'SwipeCellKit' 

您Podfile 和運行終端,並使用CD跳轉到你項目根目錄.... 然後鍵入吊艙安裝 然後打開您的根項目文件夾使用查找器 並打開YOUR_PROJECT_NAME.xcworkspace文件,問題將消失,

讓我知道如果您遇到安裝pod的任何問題。 謝謝