2016-07-14 3 views
0

私は、クラスが任意のviewControllerで初期化されると再利用できる基本的な機能を持つカスタムクラスを作成しています。問題は、#selectorで呼び出されているビューや関数を参照する方法がわかりません。エラーが発生します。未解決の識別子 "view"の使用。誰でもそれがどのように行われたか知っていますか?下のサンプルは、新しいUIButtonを作成することです。カスタムクラスのビューとセレクタのリファレンス

import Foundation 
import UIKit 

class Utils { 

var newUpdatesBtn: UIButton! 

func setupButtonNewUpdates() { 
    newUpdatesBtn = UIButton(type: UIButtonType.System) // .System 
    newUpdatesBtn.setTitle("New Updates", forState: UIControlState.Normal) 
    newUpdatesBtn.bounds = CGRect(x: 0, y: 0, width: 123, height: 27) 
    newUpdatesBtn.center = CGPoint(x: view.bounds.width/2, y: 90) // 80 point button, 20 point status bar, 40 point half button, 8 point margins 
    newUpdatesBtn.setBackgroundImage(UIImage(named: "new-updates"), forState: UIControlState.Normal) 
    newUpdatesBtn.titleLabel?.font = UIFont.systemFontOfSize(14) 
    newUpdatesBtn.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal) 
    newUpdatesBtn.addTarget(self, action: #selector(newUpdatesButtonPressed), forControlEvents: UIControlEvents.TouchUpInside) 
    self.newUpdatesBtn.alpha = 0; 
    self.navigationController!.view.addSubview(newUpdatesBtn) 
    UIView.animateWithDuration(0.3, animations: {() -> Void in 
     self.newUpdatesBtn.alpha = 1; 
    }) 
} 

} 

(問題線)

ビュービュープロパティ内の任意の参照を設定していないので、 .bounds.width

newUpdatesBtn.addTarget(self, action: #selector(newUpdatesButtonPressed), forControlEvents: UIControlEvents.TouchUpInside) 
+0

ViewControllerで 'newUpdatesButtonPressed'または' Utils'クラスを実装しますか? – Paulw11

+0

返事をありがとう。 Utilsクラスの中にあるnewUpdatesButtonPressedを実装するには、複数のViewControllerが必要です。したがって、基本的には、必要な場所でそのクラスメソッドを初期化して使用します。 – user3712837

+2

あなたのクラスは単純に「Utils」です。 View Controllerから継承しないので、 'view'や' navigationController'のようなプロパティにアクセスすることはできません。 – Aaron

答えて

1

これがあります。 あなたはこのように行うことができます。

func setupButtonNewUpdates(targetView:UIView) 
{ 
newUpdatesBtn = UIButton(type: UIButtonType.System) // .System 
. 
. 
. 
newUpdatesBtn.center = CGPoint(x: targetView.bounds.width/2, y: 90) // 80 point button, 20 point status bar, 40 point half button, 8 point margins 
. 
. 
. 
targetView.addSubView(newUpdatesBtn); 
} 

今、あなたはどんなのViewControllerからこのメソッドを呼び出したときには、単にそのVCのビューを渡します。

var util:Utils = new Utils(); 
util.setupButtonNewUpdates(self.view); 
+0

返信いただきありがとうございます。これがどのように正確に行われたかを知っておいてください。上の他のコメントと一緒に行くには、おそらくもっと一般的なケースでこれを使うべきです。 – user3712837

関連する問題