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: 17

0
votes
answers
49 views
+10

發送按鈕上的值點擊從UIView到它的超級視圖的超級視圖(UIViewController)-iOS

0

我有一個叫做HomeViewController的ViewController。它的子視圖是(UIView)。 ActivityView的子視圖是ActivityCard(UIView)。在ActivityCard中,我有一個名爲Enter的按鈕。在它的點擊我需要將所有文本域的值從ActivityCard xib發送到HomeViewController並從那裏調用一個API。我以前從未與xib合作過,因此無法管理這種情況。任何幫助將不勝感激!發送按鈕上的值點擊從UIView到它的超級視圖的超級視圖(UIViewController)-iOS

編輯:

ActivityCard.h

@interface ActivityCard : UIView 


- (IBAction)actionEnterClick:(id)sender; 
@property (weak, nonatomic) IBOutlet UILabel *lblActivityCount; 
@property (weak, nonatomic) IBOutlet UIButton *enterButton; 

@end 

ActivityView.h

@interface ActivityView : UIView 

@property (strong) ActivityCard *card; 
@property (weak, nonatomic) IBOutlet iCarousel *carousel; 

@end 

ActivityView.m

- (UIView *)carousel:(__unused iCarousel *)carousel viewForItemAtIndex:(NSInteger)index reusingView:(UIView *)view 
{ 
if (view == nil) 
    { 
     _card = (ActivityCard*) [[[NSBundle mainBundle] loadNibNamed:@"ActivityCard" owner:nil options:nil] objectAtIndex:0]; 

     _card.frame = CGRectMake(0, 0, 280.0, 350.0); 
     _card.layer.cornerRadius = 10.0f; 
     view = _card; 
    } 
    return view; 
} 

HomeViewController.h

@interface HomeViewController : UIViewController 

@property (strong) ActivityView *viewActivity; 

@end 

HomeViewController.m

_viewActivity = (ActivityView*) [[[NSBundle mainBundle] loadNibNamed:@"ActivityView" owner:nil options:nil] objectAtIndex:0]; 
    _viewActivity.frame = CGRectMake(0.0f, 0.0f, _viewContainer.frame.size.width, _viewContainer.frame.size.height); 
    [_viewActivity updateActivityUI]; 

    for (UIView *child in _viewContainer.subviews) { 
     [child removeFromSuperview]; 
    } 
    [_viewContainer addSubview:_viewActivity]; 

    [_viewActivity.card.enterButton addTarget:self action:@selector(enterButtonDidTouch) forControlEvents:UIControlEventTouchUpInside]; 

    [_viewActivity.card.lblActivityCount setText:@"11"]; 

,當我們需要加載一個按鈕點擊ActivityView此代碼已被寫入。

沙发
0
1

有很多方法可以做到這一點,我會告訴你一種方式,我認爲這是最簡單的方法。

  • ActivityCard.h
  • HomeViewController添加動作爲您Enter Button使用下面我的代碼創建Enter Button您所有的文本框的propertyproperty

    [self.activityView.cardView enterButton addTarget:self action:@selector(enterButtonDidTouch) forControlEvents:UIControlEventTouchUpInside]; 
    
  • HomeViewController.menterButtonDidTouch

    - (void)enterButtonDidTouch { 
        NSString *textOfTextField1 = self.activityView.activityCard.textField1.text; 
        // With the same way you can get others text of text fields and use them 
    } 
    
+0

的方法在某種程度上是沒有得到所謂的創建方法。任何我可能會缺少的東西? – Dia

+0

當我嘗試將標籤文本從HomeViewController設置爲ActivityCard時,它沒有正確設置值。我試過了:[_viewActivity.card.lblActivityCount setText:@「11」]; – Dia

+0

正如我所見,你做對了。你能告訴我你是如何實施它們的嗎? @Dia – trungduc

0
votes
answers
25 views
+10

從C++文件調用Objective-C的方法

-1

我從UnityBridge.mm文件調用BLEObject.m中的方法。從C++文件調用Objective-C的方法

BLEObject.m具有

- (void) SendSetting:(NSData*)data forSelected:(NSString*)type with:(NSData*)clublength and:(NSData*)clubloft{ 
} 

UnityBridge.mm具有

void bleplugin_sendSetting(unsigned char data, char* type, float clublength, float clubloft) 
{ 
    BLEObject *bleobj = [[BLEObject alloc] init]; 
    //NSString* objcstring = @(type); 
    NSString* string = [NSString stringWithUTF8String:type]; 
    NSData *data_ = [NSData dataWithBytes: &data length: sizeof(data)]; 
    NSData *clublength_ = [NSData dataWithBytes: &clublength length: sizeof(clublength)]; 
    NSData *clubloft_ = [NSData dataWithBytes: &clubloft length: sizeof(clubloft)]; 
    [bleobj SendSetting:data_ forSelected:string with:clublength_ and:clubloft_]; 
    return; 
} 

我有一個錯誤;

[bleobj SendSetting:data_ forSelected:string with:clublength_ and:clubloft_];用如下面的圖像中示出的期望的表達:

Enter image description here

+1

請添加頭文件。 –

+0

並且不被接受。我改爲and_together_with。 - (void)SendSetting:(NSData *)數據forSelected:(NSString *)類型與:(NSData *)clublength and_together_with:(NSData *)clubloft; – batuman

+1

問題是什麼? –

沙发
0
0

and在C關鍵字++;它在語法上與您寫下&&相同。 (類似地,對於or||not!not_eq!=bitand&bitor|xor^compl~and_eq&=or_eq|=爲,並xor_eq^=)。

因此,當您使用C++時,您應該避免使用這些名稱的任何標識符。

0
votes
answers
28 views
+10

Objective C: Reading text files

I've done this before, but its not working for me now. I'm doing:

NSString* path = [[NSBundle mainBundle] pathForResource:@"test" 
                                                 ofType:@"txt"];
NSString* content = [NSString stringWithContentsOfFile:path
                                              encoding:NSUTF8StringEncoding
                                                 error:NULL];
NSLog(@"%@",path);

and it returns (null) every time when I NSLog path and content. Can anyone see what I'm doing wrong?

0
votes
answers
55 views
+10

如何知道我的程序是否啓用了ARC?

12

我使用Xcode項目嚮導創建了一個支持ARC的項目。與沒有ARC支持的程序相比,我沒有注意到任何差異。是否有任何提示可以告訴我,如果我的程序支持ARC?如何知道我的程序是否啓用了ARC?

我使用的XCode 4.2.1構建4D502

+4

這是不尋常的所有.m文件:你已經有三個完全正確的,有用的和獨特的答案。 :) – 2012-07-08 05:07:52

沙发
0
25

您可以使用__has_feature,也許記錄該項目是否具有ARC在控制檯這樣的:

#if __has_feature(objc_arc) 
    // ARC is On 
    NSLog(@"ARC on"); 

#else 
    // ARC is Off 
    NSLog(@"ARC off"); 

#endif 

或者,而不是僅僅記錄是否ARC是,請嘗試如果ARC打開(或關閉)編譯器產生一個錯誤是這樣的:

#if ! __has_feature(objc_arc) 
    #error This file must be compiled with ARC. Use -fobjc-arc flag (or convert project to ARC). 
#endif 
+0

我不能找到目標菜單?這是XCode的菜單嗎? – user705414 2012-07-08 03:58:40

+0

「目標」意味着您的應用程序在Xcode文件樹中名稱最多的條目。 – CodaFi 2012-07-08 03:59:50

+0

感謝qegal,我的編譯器標誌沒有任何東西。無論我選擇使用ARC還是不在嚮導中。 – user705414 2012-07-08 04:10:28

板凳
0
5

或者只是一次測試,在代碼中添加此:

NSString* dummy = [[[NSString alloc] init] autorelease]; 

如果您使用ARC,這應該會引發錯誤。如果有,ARC已啓用,一切正常,您可以再次刪除它。

地板
0
18

如果你只是想知道一次,如果你的項目有ARC,我建議使用jpalten的答案。如果你想讓你的代碼只用ARC打造,我建議你使用qegal。

不過,如果你想知道在Xcode中設置生活:

  1. 選擇導航項目。這將打開項目編輯器。
  2. 在項目編輯器中,選擇您的目標。
  3. 在項目編輯器中,單擊Build Settings(如果它尚未被選中)。
  4. 在項目編輯器中,單擊搜索框並鍵入OBJC_ARC

這將使在構建設置顯示單行線,無論是的Objective-C自動引用計數CLANG_ENABLE_OBJC_ARC(取決於你正在展示設置描述或名稱)。如果它設置爲YES,那麼您的ARC已打開。

這是您的目標選擇是否使用ARC。請注意,每個文件都可以使用不同的設置進行編譯。這是而不是你問了什麼,但既然我們已經有三個答案,我想我可能會排在第四位。 :)

看看哪些文件覆蓋ARC設置:

  1. 選擇導航項目。這將打開項目編輯器。
  2. 在項目編輯器中,選擇您的目標。
  3. 在項目編輯器中,單擊構建階段(而不是構建設置)。
  4. 展開編譯源構建階段。

在這裏,您可以看到每個文件的編譯器標誌。設置是否使用ARC的文件將包括分別指定MRR或ARC的-fno-objc-arc-fobjc-arc

+0

被標記爲有用,因爲還通知新手ARC可以被某些文件覆蓋。這可以爲我節省很多擺弄我的ARC課前文件!這有什麼問題嗎? – cate 2013-01-07 12:58:50

+0

靜態分析器不會指出什麼 - 主要是確保未由ARC編譯的代碼遵循引用計數慣例(相對於將事件返回爲+1或自動釋放)。 – 2013-02-14 19:26:16

4楼
0
1

加「-fno-objc弧」的編譯器標誌在構建階段

917
votes
answers
29 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

43
votes
answers
38 views
+10

Apple Mach-O Linker Error when compiling for device

I've just upgraded to xcode 4.0 and I can no longer deploy to iPhone, I get a Apple Mach-O Linker Error, it still works for the simulator though.

    Ld /Users/yveswheeler/Library/Developer/Xcode/DerivedData/iParcel-fkeqjcjcbbhjwhdssjptkdxzzzxh/Build/Intermediates/iParcel.build/Debug-iphoneos/iParcel.build/Objects-normal/armv7/iParcel normal armv7
    cd /Users/yveswheeler/iParcel
    setenv IPHONEOS_DEPLOYMENT_TARGET 3.2
    setenv PATH "/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin:/Developer/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin"
    /Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/g++-4.2 -arch armv7 -isysroot /Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS4.3.sdk -L/Users/yveswheeler/Library/Developer/Xcode/DerivedData/iParcel-fkeqjcjcbbhjwhdssjptkdxzzzxh/Build/Products/Debug-iphoneos -F/Users/yveswheeler/Library/Developer/Xcode/DerivedData/iParcel-fkeqjcjcbbhjwhdssjptkdxzzzxh/Build/Products/Debug-iphoneos -filelist /Users/yveswheeler/Library/Developer/Xcode/DerivedData/iParcel-fkeqjcjcbbhjwhdssjptkdxzzzxh/Build/Intermediates/iParcel.build/Debug-iphoneos/iParcel.build/Objects-normal/armv7/iParcel.LinkFileList -dead_strip -all_load -ObjC -lxml2 -miphoneos-version-min=3.2 -framework UIKit -framework CoreGraphics -framework QuartzCore /Users/yveswheeler/Library/Developer/Xcode/DerivedData/iParcel-fkeqjcjcbbhjwhdssjptkdxzzzxh/Build/Products/Debug-iphoneos/libThree20.a /Users/yveswheeler/Library/Developer/Xcode/DerivedData/iParcel-fkeqjcjcbbhjwhdssjptkdxzzzxh/Build/Products/Debug-iphoneos/libThree20Core.a /Users/yveswheeler/Library/Developer/Xcode/DerivedData/iParcel-fkeqjcjcbbhjwhdssjptkdxzzzxh/Build/Products/Debug-iphoneos/libThree20Network.a /Users/yveswheeler/Library/Developer/Xcode/DerivedData/iParcel-fkeqjcjcbbhjwhdssjptkdxzzzxh/Build/Products/Debug-iphoneos/libThree20Style.a /Users/yveswheeler/Library/Developer/Xcode/DerivedData/iParcel-fkeqjcjcbbhjwhdssjptkdxzzzxh/Build/Products/Debug-iphoneos/libThree20UI.a /Users/yveswheeler/Library/Developer/Xcode/DerivedData/iParcel-fkeqjcjcbbhjwhdssjptkdxzzzxh/Build/Products/Debug-iphoneos/libThree20UICommon.a /Users/yveswheeler/Library/Developer/Xcode/DerivedData/iParcel-fkeqjcjcbbhjwhdssjptkdxzzzxh/Build/Products/Debug-iphoneos/libThree20UINavigator.a -framework AddressBook -lz.1.2.3 -framework Foundation -framework CFNetwork -framework MobileCoreServices -framework SystemConfiguration -framework MessageUI -framework AudioToolbox -o /Users/yveswheeler/Library/Developer/Xcode/DerivedData/iParcel-fkeqjcjcbbhjwhdssjptkdxzzzxh/Build/Intermediates/iParcel.build/Debug-iphoneos/iParcel.build/Objects-normal/armv7/iParcel

arm-apple-darwin10-g++-4.2.1: /Users/yveswheeler/Library/Developer/Xcode/DerivedData/iParcel-fkeqjcjcbbhjwhdssjptkdxzzzxh/Build/Products/Debug-iphoneos/libThree20.a: No such file or directory
arm-apple-darwin10-g++-4.2.1: /Users/yveswheeler/Library/Developer/Xcode/DerivedData/iParcel-fkeqjcjcbbhjwhdssjptkdxzzzxh/Build/Products/Debug-iphoneos/libThree20Core.a: No such file or directory
arm-apple-darwin10-g++-4.2.1: /Users/yveswheeler/Library/Developer/Xcode/DerivedData/iParcel-fkeqjcjcbbhjwhdssjptkdxzzzxh/Build/Products/Debug-iphoneos/libThree20Network.a: No such file or directory
arm-apple-darwin10-g++-4.2.1: /Users/yveswheeler/Library/Developer/Xcode/DerivedData/iParcel-fkeqjcjcbbhjwhdssjptkdxzzzxh/Build/Products/Debug-iphoneos/libThree20Style.a: No such file or directory
arm-apple-darwin10-g++-4.2.1: /Users/yveswheeler/Library/Developer/Xcode/DerivedData/iParcel-fkeqjcjcbbhjwhdssjptkdxzzzxh/Build/Products/Debug-iphoneos/libThree20UI.a: No such file or directory
arm-apple-darwin10-g++-4.2.1: /Users/yveswheeler/Library/Developer/Xcode/DerivedData/iParcel-fkeqjcjcbbhjwhdssjptkdxzzzxh/Build/Products/Debug-iphoneos/libThree20UICommon.a: No such file or directory
arm-apple-darwin10-g++-4.2.1: /Users/yveswheeler/Library/Developer/Xcode/DerivedData/iParcel-fkeqjcjcbbhjwhdssjptkdxzzzxh/Build/Products/Debug-iphoneos/libThree20UINavigator.a: No such file or directory
Command /Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/g++-4.2 failed with exit code 1
沙发
+50

To add onto the list of weird stuff that fixed this issue...

I had some const CGFloat variables in a global header file like so

const NSInteger  globalInteger1 = 2;
const NSInteger  globalInteger2 = 3;

The moment I removed these, all was fine :)

板凳
+50

I had exactly the same problem just because I had two same constants in different classes. You also can have this problem if you import .m file not .h file

雅已經做到了。即使你2年後。謝謝 ! - teck wei 2017年4月18日12:59

地板
+40

Not sure if it's related, but seeing that you're running some three20 libraries, you may want to check this post on their website: http://three20.info/article/2011-03-10-Xcode4-Support

4楼
+40

I had the same problem, and I solved it. In my case, "architectures" setting caused the problem. In my project file, Build Settings tab, Architectures were set to armv6. I changed it to Standard(armv7), do clean and build. Then it worked!

5楼
+40

In my case the problem was having different architectures specified under different targets. I was building my application target with armv6, armv7 and cocos2d with Standard (amrv7). Go into build settings and make sure your architectures agree for all targets.

6楼
+40

I solved this problem too weird !

Go to Target > Build Phases > Link Binary with libraries :

Remove all your frameworks and add them again !

Hope it works for you !

非常糟糕的解決方案 - SleepsOnNewspapers 2015年4月26日1:47

它不能回答......不合邏輯 - LKM 2015年6月1日3:34

我檢查了錯誤消息,發現它是框架之一,所以我刪除了該框架並再次添加它,而不是所有框架,只是那個。 - Oluwatobi Omotayo於18年8月24日19:07

7楼
+40

For Swift language ...

I am getting this error " ld: file too small (length=0) .... "

In my case I just clean the project and then rebuild it ..

Steps:-

1) goto Project -> Clean

2) goto Project -> Build

Hope this helps..

為我工作。當我將設備從iPhone 6切換到iPhone 4S時發生了。 - racl101 2015年8月4日3:16

也為我工作。非常感謝 - Lee Mar於2016年3月29日9:48

8楼
+40

This did a trick for me:

Go to

1) Products > clean

2) Windows > Projects

3) Select your project and click on "Delete" derived Data

4) Products > Build

9楼
+30

One possibility: Turn on "Dead code stripping" in the Xcode 4 build settings.

Another possibility: It could be that you switched to using LLVM for some framework that was previously using GCC. Moving back to GCC (or LLVM GCC) may get rid of those warnings.

10楼
+30

I mistakenly defined a new constant with the same name as an existing constant in a different file and it caused this error for me using xCode 4.3.1. xCode didn't complain but the compiler doesn't like it.

11楼
+30

I was able to fix this error by editing "Library Search Paths"

It cropped up in the first place because I had moved a couple folders around, and that ended up giving my build settings two different search paths because they are are automatically added to your build settings when you link a library/framework, but they are not always removed.

So if you move a linked library/framework to a different directory and re-link it, you'll have to manually edit the search path.

You might be able to dodge this by removing the library/framework before moving it, but I haven't tested that.

0
votes
answers
24 views
+10

多線程iOS,快速啓動UI

-1

在我的ios應用程序中,我已經包括谷歌,臉譜和推特整合。當應用程序啓動時,它在加載UI之前加載API。多線程iOS,快速啓動UI

如何以我的UI加載多線程首先快速啓動。我didFinishLaunchingWithOptions是。

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { 

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ 
     // Add code here to do background processing 
     // 
     // 

     NSLog(@"Thread Excecution started"); 

     NSError* configureError; 
     [[GGLContext sharedInstance] configureWithError: &configureError]; 
     NSAssert(!configureError, @"Error configuring Google services: %@", configureError); 

     [GIDSignIn sharedInstance].delegate = self; 


     [[FBSDKApplicationDelegate sharedInstance] application:application 
           didFinishLaunchingWithOptions:launchOptions]; 

     dispatch_async(dispatch_get_main_queue(), ^{ 
      // Add code here to update the UI/send notifications based on the 
      // results of the background processing 

      NSLog(@"Thread Excecution completed"); 
     }); 
    }); 
    return YES; 
} 
+0

您知道,即使在主線程中,通知實際上可能會觸發並被接收,但無法保證嗎?你確定要這麼做嗎? – NSNoob

+0

爲什麼你需要在後臺線程中編寫外部API的啓動代碼呢? – NSNoob

+0

我可以在Viewdidload中添加這些代碼嗎?是的,將工作 – Saranjith

沙发
0
2

如果您使用多個線程,那麼您可以使用dispatch_group的概念。

dispatch_group_t group = dispatch_group_create(); 

//block 1 
dispatch_group_async(group, dispatch_get_global_queue(0, 0), ^{ 
    // code here 
}); 
//block 2 
dispatch_group_async(group, dispatch_get_global_queue(0, 0), ^{ 
    // code here 
}); 

//block 3 
dispatch_group_notify(group, dispatch_get_global_queue(0, 0), ^{ 
    // block 3 will get notify, after block 1 and block 2 complete their tasks. 
dispatch_async(dispatch_get_main_queue(), ^{ 

     [animationImageView stopAnimating]; 

     [self createUI]; 
    }); 
} 

在這裏,塊1和塊2將平行地運行,並且在他們完成他們的工作之後,塊3將得到通知。

0
votes
answers
35 views
+10

Xcode儀器問題

-1

現在我面臨着儀器的奇怪問題。構建項目,在模擬器上啓動它,當我想用??儀器(例如 - Object Allocations)檢查我的項目時,什麼都不會發生。 Instruments.app負載,這就是全部!當我嘗試手動加載ObjectAlloc.tracetemplate,顯然它加載,但我不能選擇我要檢查的對象。Xcode儀器問題

此外,當我手動運行儀器,在早期是現在的工具的觀點僅是一個工具 - 所謂BLANK :(

我想這是發生,因爲我最近更新的Xcode

。類似的問題我已經找到Can't run Instruments from Xcode但沒有導致此問題的解釋

感謝

編輯:!通過重新安裝Xcode中解決了這個問題!

沙发
0
2

編輯:重新安裝Xcode中解決了這個問題!

434
votes
answers
34 views
+10

How can I load storyboard programmatically from class?

My problem is that I was looking for way to use both storyboard and xib. But I can't find proper way to load and show storyboard programmatically. Project was started developing with xib, and now it's very hard to nest all xib files in storyboard. So I was looking a way to do it in code, like with alloc, init, push for viewControllers. In my case I have only one controller in storyboard: UITableViewController, which has static cells with some content I want to show. If anyone knows proper way to work both with xib and storyboard without huge refactoring, I will appreciate for any help.

up vote 351 down vote accepted favorite
沙发
+3510
+50

在故事板中,轉到“屬性”檢查器並設置視圖控制器的標識符。然後,您可以使用以下代碼顯示該視圖控制器。

  UIStoryboard * sb = [UIStoryboard storyboardWithName:@“MainStoryboard”bundle:nil]; UIViewController * vc = [sb instantiateViewControllerWithIdentifier:@“myViewController”]; vc.modalTransitionStyle = UIModalTransitionStyleFlipHorizo??ntal; [self presentViewController:vc animated:YES completion:NULL];  
     
			
        

如果你想在場景的默認視圖控制器上啟動,[sb instantiateInitialViewController]很方便。 - drewish 12月15日在4:31

詹姆斯,謝謝!我一直在尋找相當長的時間來弄清楚如何實例化Storyboard的視圖。你的回答(和kokoko的問題)是最令人耳目一新的。 - bejonbee於2012年7月17日19:23

在James Beith的代碼中,如果使用當前的viewcontroller來回切換,必須重用UIViewControler * vc。我發現vc很難繞到並且連接到故事板筆尖,直到用戶按下新視圖上的按鈕,現在有一個內存洩漏,這個丟棄的vc來自此代碼的先前咒語。 - SWoo 2014年2月6日19:48

如果有人想知道如何在app委託中執行此操作,則按以下順序將[self presentViewcontroller]邏輯替換為這些行:1)self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds ]]; 2)self.window.rootViewController = vc; 3)[self.window makeKeyAndVisible];。您也可以擺脫modalTransitionStyle行,因為這不是來自app delegate的模態轉換。 - lewiguez 2014年4月13日4:50

僅供參考,如果您想“推”新故事板而不是模態彈出,請查看chaithraVeeresh的答案。 - Adam Johns 2014年10月27日18:13

+610
>

IB&gt; 顯示身份檢查器&gt; 身份&gt; 故事板ID

Swift(遺留)

 讓storyboard = UIStoryboard(名稱:“Main”,bundle:nil)讓vc = storyboard.instantiateViewControllerWithIdentifier(“viewController”)為?UIViewController self.navigationController!.pushViewController(vc!,animated:true)  

編輯:Swift 2在評論中建議 Fred A.

在Swift 2中,你不需要添加“as?UIViewController”,編譯器會自動確定它 - FrédéricAda2015年10月8日20:03

或者你可以做self.storyboard並合併line1&2 - Honey 2016年9月18日22:30

+160

在屬性檢查器中為該視圖控制器提供標識符,以下代碼適用於我

  UIStoryboard * storyboard = [UIStoryboard storyboardWithName:@“MainStoryboard”bundle:nil]; DetailViewController * detailViewController = [storyboard instantiateViewControllerWithIdentifier:@“DetailViewController”]; [self.navigationController pushViewController:detailViewController animated:YES];  
     
			
        
+30

試試這個

  UIStoryboard * mainStoryboard = [UIStoryboard storyboardWithName:@“Main”bundle:nil]; UIViewController * vc = [mainStoryboard instantiateViewControllerWithIdentifier:@“Login”]; [[UIApplication sharedApplication] .keyWindow setRootViewController:vc];  
     
			
        

如果您沒有使用UINavigationController,請使用此項,如其他答案所示 - latenitecoder 17年10月10日在22:45

+20

在swift
NavigationController pushController 中,您可以替換為

  present(vc,animated:true,completion:nil) ) 
     
			
        
+10

對於 swift 3和4 ,您可以執行此操作。好的做法是設置Storyboard的名稱等於StoryboardID。

  enum StoryBoardName {case second =“SecondViewController”}擴展名UIStoryBoard {class func load(_ storyboard:StoryBoardName) - &gt; UIViewController {return UIStoryboard(name:storyboard.rawValue,bundle:nil).instantiateViewController(withIdentifier:storyboard.rawValue)}}   

然後你可以在你的ViewController中加載你的Storyboard,如下所示:

 類MyViewController:UIViewController {override func viewDidLoad(){super.viewDidLoad()guard let vc = UIStoryboard.load(.second)as?SecondViewController else {return} self.present(vc,animated:true,
     
			
        
0

你總是可以直接跳到根控制器:

  UIStoryboard * storyboard = [UIStoryboard storyboardWithName:@“Main”bundle:nil]; UIViewController * vc = [storyboard instantiateInitialViewController]; vc.modalTransitionStyle = UIModalTransitionStyleFlipHorizo??ntal; [self presentViewController:vc animated:YES completion:NULL];  
     
			
        
0
votes
answers
35 views
+10

目標C線程問題

4

下面的代碼:目標C線程問題

for(int i = 0; i < personListViewController.peopleCount; i++) { 
    [NSThread detachNewThreadSelector:@selector(getPerson:) toTarget:self withObject:i]; 
} 

getPerson看起來是這樣的:

- (void)getPerson:(int)whichPerson { } 

當我建立這個,我得到如下:警告:傳遞detachNewThreadSelector的」說法三: toTarget:withObject:'使指針從整數沒有鑄造

我想要做的就是通過一個int傳遞給getPerson通過detachNewThrea dSelector和我無法弄清楚如何讓它採取任何東西,但對象指針。我在這裏錯過了什麼?

沙发
0
12

您作爲-[NSThread detachNewThreadSelector:toTarget:withObject:]的第一個參數傳遞的選擇器必須採用類型爲id(指向對象實例的指針)的單個參數。雖然你可以玩遊戲(在大多數平臺上),但是指針的大小與int相同,並將您的值轉換爲id,然後返回int,但不應該依賴此行爲。相反,編寫一個包裝方法,該方法採用NSNumber參數並將int包裝在NSNumber中。該包裝方法的實現可能是:然後

- (void)getPersonWithNumber:(NSNumber*)number { 
    [self getPerson:[number integerValue]]; 
} 

你的循環將

for(NSInteger i = 0; i < personListViewController.peopleCount; i++) { 
     [NSThread detachNewThreadSelector:@selector(getPersonWithNumber:) toTarget:self withObject:[NSNumber numberWithInteger:i]; 
} 

請注意,我已經從int轉換爲NSInteger貫穿始終。除非您使用int的遺留代碼進行接口連接,否則您應該使用NSInteger,這是在新Cocoa代碼中每個平臺(32位或64位)上的適當大小整數的typedef。

+0

這樣做。謝謝你一百萬次。在objective-c中,我經常會遇到那些小事情。 – lewsid 2009-07-22 17:14:01

板凳
0
4

您需要將整數包裝在NSNumber類中,以使該數字成爲對象。

[NSThread detachNewThreadSelector:@selector(getPerson:) toTarget:self withObject:[NSNumber numberWithInteger:i]]; 

NSThread不採用原語(如int或char),所以你必須使用NSNumber!

希望有所幫助。