カテゴリー
iOS Swift

iOS & Swift 101(初歩)Part 3

ViewController内でUIエレメントの配置に慣れてきたら、次は簡単なclassを作ってみることをおすすめします。

プロジェクトナビゲーターのプロジェクトファイルを右クリック->New File->Swift Fileを選択、ファイル名(class名)を記入して新規ファイルを作成します。

PlaySoundという名前のclassを作ることにし、その中のmember variable(メンバ変数)として、拍子を表すmeterを定義してみます。

class PlaySound {
  
  public var meter: Int = 4
  
}

これをViewControllerで使うには、以下のようにします。

// ViewController.swift

class ViewController: UIViewController {
  
  let playSound = PlaySound()
  
  override func viewDidLoad() {
    super.viewDidLoad()
    
    print(playSound.meter)
 
  }
}

class PlaySound内に関数を作り、それを介してmeterにアクセスすることも可能です。

変数や関数はAccess Controlを定義することが出来ます。publicは自身以外のclassからもアクセスが可能、privateはそのclass自身以外からのアクセスが不可になります。これは将来的により安全でわかりやすいコードを書く時に役に立ちますが、いまはそれほど気にしなくても良いと思います

// PlaySound.swift

class PlaySound {
  
  private var meter: Int = 4
  
  public func printMeter() {
    print(meter)
  } 

  public func getMeter() -> Int {
    return meter
  }
}
// ViewController.swift

class ViewController: UIViewController {
  
  let playSound = PlaySound()
  
  override func viewDidLoad() {
    super.viewDidLoad()
    
    // playSoundで定義したprintする関数
    playSound.printMeter()
    // playSoundからInt型の返り値をprintする処理
    print(playSound.getMeter())
 
  }
}
カテゴリー
C++

C++ の文法

C++の文法について、個人的なメモ

Stack vs Heap

Objectをinstantiateする時、メモリをstackとheapどちらからallocateするかによって処理内容と文法が大きく違います。

struct Vector3 {
  float x, y, z;

  Vector3()
    : x(10), y(11), z(12) {}
};

// stack
// int
int value = 5;
// array. allocating 5 * int size in memory
int array[5];
array[0] = 1;
array[1] = 2;
array[2] = 3;
array[3] = 4;
array[4] = 5;
// object
Vector3 vector;

// heap
// int
int* hvalue = new int;
*int = 5;
// array
int* harray = new int[5];
harray[0] = 1;
harray[1] = 2;
harray[2] = 3;
harray[3] = 4;
harray[4] = 5;
// object, () is optional
Vector3* hvector = new Vector3();

// you need to manually call delete to deallocate
delete hvalue;
delete[] harray;
delete hvector;

stackにvariableをallocateする時は、”stack pointer”がメモリ上でvariableのサイズだけ移動させ、メモリを次々とallocateする(stack)ので、動作がとても早いです。variableのscopeが終わると自動的にdeallocateされます。

heapの場合はallocateの時newで「free list(メモリ領域にあるavailableなメモリのリスト)」からavailableなメモリブロックを探しだし、確保し、そのpointerをdereferenceした上で、値を代入します。また、明示的に delete(deallocate)する必要があります。もしApplicationに割り当てられた以上のメモリが必要になると、Applicationはsystemに要求します。つまりとても「コストが高い」オペレーションです。

smart pointers の場合は裏でこのnew、deleteが呼ばれています。

可能な限りstackにメモリをallocateする方が良い、ということです。

PointerReference

int a = 5;
int* ptr = &a;
std::cout << *a << std::endl; // prints 5 (value of a)

int& ref = a;  // ref is now an alias of a
ref = 2;
std::cout << a << std::endl; // prints 2

Constructor

このThe Chernoのtutorialで説明されているように、initializer listによるinitializationは、member variableを一度だけinstantiateするため効率が良いです。また、initializer listによるinitializationはinitializer listの順番ではなく、member variableが宣言されている順に実行されるため、dependencies(どのmemberが先にinitializeされなくてはならないか、など)に関して気をつけなければなりません。

class Entity {

public:
  // a constructor without parameter
  Entity {
  }
 // a constructor with initializer lists
  Entity(float x, float y)
    : X(x), Y(y) // it needs to be in the same order as you declared
  {
  }
  // a constructor with parameters
  Entity(float x, float y) {
    X = x;
    Y = y;
  }
  float X, Y;
}

class Log {

public:
  // by assigning delete, can disable default constructor
  Log() = delete;
}

Copy Constructor

// example of deep copy...
class Entity {
public:
  Entity() {} // default constructor
  // copy constructor
  Entity(const Entity& other) {
    m_X = other.m_X;
  }
  int m_X;
}

Smart Pointers

//unique pointer

// shared pointer

// weak pointer

Macro

// example
#define LOG(x) std::cout << x << std::endl

Namespace alias

// example...
using MidiKeyboardStateListener = MidiKeyboardState::Listener;

Const

const int MAX_AGE = 90;
int* a = new int; // a is a pointer
*a = 2; // you can dereference a and assign 2
a = (int*)&MAX_AGE // you can reassign pointer

const int* a = new int; // add "const" keyword to a pointer
// you can also write it as "int const* a"
*a = 2; // error, you can't modify the contents of the pointer
a = (int*)&MAX_AGE; // no error
std::cout << *a << std::endl; // reading a works

int* const a = new int;
*a = 2; // this works
a = (int*)&MAX_AGE; // error
a = nullptr; // error

class Entity {
private: 
  int m_X, m_Y;

public:
  int GetX() const { // it means the function can't modify the value
                     // read only method
                     // good for getters
    m_X = 2;  // can't do this
    return m_X;
  }

  void SetX(int x) {  // can't have const here...
    m_X = x;
  }
}

void PrintEntity(const Entity& e) {
  std::cout << e.GetX() << std::end;  // if I remove const from
                                      // the above GetX(), it won't work
}

const reference

non-const lvalue reference

lvalues and rvalues

lvalueはメモリ上にアドレスがある値(変数など)j

rvalueはメモリ上にアドレスがない値(記述されただけの値)

int i = 5;
int& a = 10;  // this does not work, because 10 is a rvalue
int& b = i; // this works, because i is a lvalue
const int& c = 10; // this works
// it creates a temporary behind the scenes as in the below pseudo code
int temp = 10;
int& c = temp;

Lambda — captureをthis(オブジェクト)でするか、&(オブジェクトのreference)でするか、ですが、referenceの場合はmember変数に変更を加えます。

関数の戻り値へconst keywordをつけると、戻り値はconst(変更不可)になります。

// example
juce::String getCurrentPreset() const;
カテゴリー
C++ JUCE

JUCE その2 UIの基礎

UIについては公式Tutorialを以下の順番にやるのが良いと思います。

Application Window

Component

Graphics

以下はJUCEApplicationを継承したApplication classの最小コードです。

class MainComponentTutorialApplication: public juce::JUCEApplication
{
public:
  MainComponentTutorialApplication() {}
  const juce::String getApplicationName() override
  {
    return ProjectInfo::projectName; 
  }
  const juce::String getApplicationVersion() override 
  { 
    return ProjectInfo::versionString;
  }
  bool moreThanOneInstanceAllowed() override { return true; }
  void initialize (const juce::String& commandLine) override
  {
    // [3] initializing the mainWindow instance.
    mainWindow.reset(new MainWindow(getApplicationName()));
  }
  void shutdown() override
  {
    // [4] nullifying the pointer 
    mainWindow = nullptr;
  }
  void systemRequestedQuit() override
  {
    quit();
  }

  // [1] nested class inside the application class
  class MainWindow: public juce::DocumentWindow {
  public:
    MainWindow(juce::String name): DocumentWindow(name,
                                          juce::Colours::lightgrey,
                                          DocumentWindow::allButtons)
    {
      // [1] setup
      setUsingNativeTitleBar(true);
      // [5] resize will work automatically when setResizable is set
     // you can write custom layout logic inside resized() 
     // virtual func of Component class
   setResizable(true, false);
      centreWithSize(300, 200);
      setVisible(true);
    }
    void closeButtonPressed() override
    {
      JUCEApplication::getInstance()->systemRequestedQuit();
    }
  private:
   JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(MainWindow)
  };
private:
  // [2] declare as a private member of the class. 
  // unique_ptr is a scoped pointer.
   // It gets deleted automatically when it becomes out of scope.
  std::unique_ptr<MainWindow> mainWindow;
};

この状態からComponentを追加していきます。

JUCEでは、全てのGUIエレメント(button, slider, textFieldなど)がComponentクラスを継承(derive, inherit)しています。

ApplicationにまずmainComponentを追加し、その他のGUIエレメントはmainComponentのchildrenとして追加されます。

ProjucerのFile Explorerの+ボタンをクリックし、Add New Component class(split between a CPP & header)を選択し、ファイル名をMainComponentとします。

// MainComponent.h

class MainComponent  : public juce::Component
{
public:
    MainComponent();
    ~MainComponent() override;

    // [5] two important virtual functions
    void paint (juce::Graphics&) override;
    void resized() override;

private:
    JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MainComponent)
};

Componentベースクラスには2つ重要なvirtual function(subclassでoverrideするfunction)があり、全てのcomponentで定義される必要があります。

Component::paint() はこのcomponentがスクリーン上にどのように描画されるかを定義し、

Component::resized() は画面リサイズ時の挙動を定義します。

// MainComponent.cpp
void MainComponent::paint (juce::Graphics& g)
{
    g.fillAll (juce::Colours::lightblue);
 
    g.setColour (juce::Colours::darkblue);
    g.setFont (20.0f);
    g.drawText ("Hello, World!",
                getLocalBounds(), 
                juce::Justification::centred, 
                true);
}
// Main.cpp
#include "MainComponent.h"

// MainWindow constructor
MainWindow(juce::String name): DocumentWindow(name,
                                    juce::Colours::lightgrey,
                                   DocumentWindow::allButtons)
{
  setUsingNativeTitleBar(true);

  // assigning MainComponent instance in setContentOwned()
  setContentOwned(new MainComponent(), true);

  // [6 ] in order for getWidth() and getHeight() to work, 
  // MainComponent needs to have setSize() set in it's constructor
  centreWithSize(getWidth(), getHeight());
  setVisible(true);
}
// MainComponent.cpp
MainComponent::MainComponent()
{
  setSize(400, 300);
}

[6] componentのサイズ設定し忘れはJUCEでよくあるbugの原因、、、とのことです。

これらvirtual functions はresized()、paint()の順で、componentのinitialize時に一度呼ばれます。これらは必要に応じてシステムがコールするので、プログラマーが自分でコールしてはいけません。

[5] MainWindowのconstructorでsetResizable()を設定すると、Component::resized()に何も記述しなくてもリサイズは動作します。child elementなどのレイアウトに関することをresized()に記述出来ます。

paint(juce::Graphics& g) にはGraphicsクラスのインスタンスのアドレス g が渡されています。この g を使って色々なUIエレメントを描画出来ます。ほぼ全ての場合、Graphicsクラスはpaint()内でのみ使用されます。

Fontの設定

g.setFont(20.0f); // set size of the font

juce::Font mainComponentFont ("Times New Roman", 20.0f, juce::Font::italic);
// font styles can be used as a bitmask
juce::Font mainComponentFont ("Times New Roman", 20.0f, juce::Font::bold | juce::Font::italic);
g.setFont(mainComponentFont); // can pass a Font object

// using getLocalBounds()
g.drawText(currentSizeAsString, getLocalBounds(), juce::Justification::centred, true);
// using Justification::Flags
g.drawText(currentSizeAsString, getLocalBounds(), juce::Justification::topLeft, true);
// using explicit size and position
g.drawText(currentSizeAsString, 20, 40, 200, 40, juce::Justification::centred, true);

// draws a line with 5 pixels width from (10, 300) to (590, 300), 
g.drawLine (10, 300, 590, 300, 5);
// draws a rectangle with origin (300, 120), width 200, height 170
g.drawRect (300, 120, 200, 170);
// draws a ellipse inside a rectangle with origin (530, 120), width and height 60 pixels
g.drawEllipse (530, 120, 60, 60, 3);
カテゴリー
C++ JUCE

JUCE その1、インストール

JUCE(Audio/Midi application/plug-inのためのC++フレームワーク)でVST3のMidiプラグインを作ろうと思い立ち、インストールの手順、など、忘れがちなステップを記録しておきます。公式Documentはここ

JUCEはgithubのdevelopブランチをクローンします。

git clone https://github.com/juce-framework/JUCE.git JUCE_dev
cd ./JUCE_dev
git checkout develop
// branch 'develop' set up to track 'origin/develop'.
// Switched to a new branch 'develop'

JUCE_dev -> extras -> Projucer -> Builds -> MacOSX 内のProjucer.xcodeprojを立ち上げてビルドするとProjucerアプリが立ち上がります。

ProjucerのGlobal pathsをこのJUCE_devに設定します。

  • ProjucerのメニューでNew Projectを選択
  • Plug-In -> Basicを選択、Project Nameに適当な名前を入力し、Create Project…をクリック。保存先を聞かれるので、disk内の適切な場所を選択し、Openをクリック。

VSTプラグインを作成する場合は、プロジェクト名の横のギア・アイコンをクリックし、Plugin Formatsで「VST3」「AU」「AUv3」「Standalone」、Plugin Characteristicsで「Plugin MIDI Input」「Plugin MIDI Output」にチェックを入れます。

*Standaloneにチェックを入れないとDAW上でテストが出来ません。(updated 26 Feb 2024)

Xcodeアイコンをクリックすると、設定がsaveされ、Xcodeが起動されます。Xcodeでプロジェクトをビルドすると、標準では/Users/[your_user_name]/Library/Audio/Plug-Ins/VST3にファイルが作成されます。

これをテストする時は、/Users/[your_user_name]/JUCE/extras/AudioPluginHostビルドし、メニューバーのOptions -> Edit the List of Available Pluginsを選択

左下コーナーのOptionsをクリックし、Scan for new or updated VST3 plug-insを選択

Select folders to scan に /Users/[your_user_name]/Library/Audio/Plug-Ins/VST3 が無ければ + ボタンでパスを選択し、Scanをクリック。Scan終了後は AudioPluginHostで右クリックをするとyourcompany -> TestPlugin と先ほどビルドしたPluginが選択可能になります。

TestPluginをダブルクリックすると、”Hello World!”と画面が表示されます。

開発中のPlug-Inをビルドする度にこのAudioPluginHostを立ち上げるには、Plug-InのXcodeのProduct -> Scheme -> Edit Schemeを選択、Runの中の ExecutableでOtherを選択し、ここで /Users/[your_user_name]/JUCE/extras/AudioPluginHost/Builds/MacOSX/build/Debug/AudioPluginHost を選択、Debug executableにチェックを入れます。

Logic Pro XのMidi Pluginとして動作させるにはAUv3でコンパイルする必要があります。

カテゴリー
iOS Swift

Core Data Stackを理解する

Cocoacastの良記事を勉強することでCore Dataについてより理解をしたので、忘れないように記録しておきます。

Core Dataはデータをdisk(デバイスのストレージ)に記録(persist)することが出来ますが、それはCore Dataのひとつの機能であって全てではなく、Core DataはあくまでObject Graphを管理するものです。

XcodeでUse Core Dataをチェックしてプロジェクトを作成すると、AppDelegateに最低限のコードテンプレートが用意されますが、それが逆にCore Dataを分かりにくくしている、とも言えます。

Core Data Stackの「構成部品」をひとつひとつ自分で組んでみると、全体像がより見えてくると言えます。

Core Data Stackは以下の三つから構成されます。

  • NSManagedObjectModel
  • NSPersistentStore (NSPersistentStoreCoordinator)
  • NSManagedObjectContext

これらを順序立てて組み上げて使うためのclass CoreDataManagerを用意し、必要な場面で使用します。

import UIKit
import CoreData

class CoreDataManager {
  
  private let modelName: String

  // [3]
  public typealias CoreDataManagerCompletion = () -> ()
  private let completion: CoreDataManagerCompletion
  
  // [4]
  public func privateChildManagedObjectContext() -> NSManagedObjectContext {
    let managedObjectContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
    managedObjectContext.parent = mainManagedObjectContext
    managedObjectContext.undoManager = UndoManager()
    return managedObjectContext
  }
  
  // [5]
  public func saveChanges() {
    mainManagedObjectContext.performAndWait{
      do {
        if self.mainManagedObjectContext.hasChanges {
          try self.mainManagedObjectContext.save()
        }
      } catch {
        print("Unable to save changes of Main Managed Object Context")
        print("\(error), \(error.localizedDescription)")
      }
    }
    
    privateManagedObjectContext.perform {
      do {
        if self.privateManagedObjectContext.hasChanges {
          try self.privateManagedObjectContext.save()
        }
      } catch {
        print("Unable to save changes of Private Managed Object Context")
        print("\(error), \(error.localizedDescription)")
      }
    }
  }
  
  public init(modelName: String, completion: @escaping CoreDataManagerCompletion) {
    self.modelName = modelName
    self.completion = completion
    setupCoreDataStack()
    setupNotification()
  }
  
  // [1]
  private lazy var managedObjectModel: NSManagedObjectModel = {
    guard let modelURL = Bundle.main.url(forResource: modelName, withExtension: "momd") else {
      fatalError("can't get momd url")
    }
    guard let mom = NSManagedObjectModel(contentsOf: modelURL) else {
      fatalError("failed to create model from file: \(modelURL)")
    }
    return mom
  }()
  
  private lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
    let psc = NSPersistentStoreCoordinator(managedObjectModel: managedObjectModel)
    // adding persistentStore in a background thread in addPersistentStore() below
    return psc
  }()

  // [3]
  private func addPersistentStore(to persistentStoreCoordinator: NSPersistentStoreCoordinator) {
    let dirURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last
    let fileURL = URL(string: "\(modelName).sqlite", relativeTo: dirURL)
    do {
      try persistentStoreCoordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: fileURL, options: [
        NSMigratePersistentStoresAutomaticallyOption: true,
        NSInferMappingModelAutomaticallyOption: true
      ])
    } catch {
      fatalError("error configuring persistent store: \(error)")
    }
  }
  
  private func setupCoreDataStack() {
    guard let persistentStoreCoordinator = mainManagedObjectContext.persistentStoreCoordinator else {
      fatalError("unable to set up Core Data Stack")
    }
    // [3]
    DispatchQueue.global().async {
      self.addPersistentStore(to: persistentStoreCoordinator)
      DispatchQueue.main.async {
        self.completion()
      }
    }
  }
  
  private func setupNotification() {
    let notificationCenter = NotificationCenter.default
    notificationCenter.addObserver(self, selector: #selector(onNotifyBackground), name: UIApplication.willResignActiveNotification, object: nil)
    notificationCenter.addObserver(self, selector: #selector(onNotifyBackground), name: UIApplication.didEnterBackgroundNotification, object: nil)
  }
  
  @objc private func onNotifyBackground(_ notification: Notification) {
    saveChanges()
  }

  // [2]
  private lazy var privateManagedObjectContext: NSManagedObjectContext = {
    let managedObjectContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
    managedObjectContext.persistentStoreCoordinator = persistentStoreCoordinator
    return managedObjectContext
  }()
  
  // [2]
  public private(set) lazy var mainManagedObjectContext: NSManagedObjectContext = {
    let managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
    managedObjectContext.parent = privateManagedObjectContext
    return managedObjectContext
  }()
}

[1] extensionがmomdとなっていますが、これはxcdatamodeldを元にコンパイルされた、より小さな(効率の良い)ファイルです。

[2] NSManagedObjectContextは動作するスレッド(メインスレッドもしくはプライベート(バックグラウンド))を指定出来ます。stack上にcontextは複数あってもよく、例えばdiskに記録するなどの作業はメインスレッドで行われるとUIをブロックしてしまう可能性があるため、バックグラウンドで行うようにするなどの目的別に分けることが出来ます。

[3] persistentStoreCoordinatorにpersistentStoreを追加する際は、状況により少し時間がかかる場合があるため、処理をバックグラウンドで行い、処理完了後の作業をコールバック関数内で行えるようにしています。

[4] mainManagedObjectContextをparentとするprivateChileManagedObjectContextを用意し、UIViewControllerなで使用するためのもの。

[5] 各contextはsave( )する事に、自身とparentに保存内容をpushします。mainManagedObjectContextがsave( )し終わるのを待ち、その後privateManagedObjectContextがsave( )し、diskに記録されるという流れです。

カテゴリー
iOS Swift

UIViewをドラッグしRectangleを描く

よくある、指のドラッグに応じて「選択中」の四角いviewを画面に表示する方法。

指のドラッグに応じてシェイプを描く方法はこのSO記事、DashedUIView(UIViewのBorderを破線 dashed にする)についてはこちらのSO記事を参考にしました。

class ViewController: UIViewController {
  
  var initialPoint: CGPoint = .zero
  
  lazy var overlay: CustomDashedView = {
    let view = CustomDashedView()
    view.dashColor = .systemPink
    view.dashWidth = 1
    view.dashLength = 5
    view.betweenDashesSpace = 2
    return view
  }()
  
  override func viewDidLoad() {
    super.viewDidLoad()

    view.addSubview(overlay)
    let panGesture = UIPanGestureRecognizer(target: self, action: #selector(onViewSelected))
    view.addGestureRecognizer(panGesture)
  }
  
  @objc func onViewSelected(_ sender: UIPanGestureRecognizer) {
    let location = sender.location(in: view)
    if sender.state == .began {
      initialPoint = location
    }
    if sender.state == .changed {
    // comparing the initialPoint and the current location, and get the smaller value for the x and y coordinate, set it as the origin of the rect
   // abs() gives the absolute value
    let rect = CGRect(x: min(initialPoint.x, location.x), y: min(initialPoint.y, location.y), width: abs(initialPoint.x - location.x), height: abs(initialPoint.y - location.y))
      print(rect)
      overlay.frame = rect
    }
    if sender.state == .ended {
      overlay.frame.size = .zero
    }
  }
}


class CustomDashedView: UIView {

    var cornerRadius: CGFloat = 0 {
        didSet {
            layer.cornerRadius = cornerRadius
            layer.masksToBounds = cornerRadius > 0
        }
    }
    var dashWidth: CGFloat = 0
    var dashColor: UIColor = .clear
    var dashLength: CGFloat = 0
    var betweenDashesSpace: CGFloat = 0

    var dashBorder: CAShapeLayer?

    override func layoutSubviews() {
        super.layoutSubviews()
        dashBorder?.removeFromSuperlayer()
        let dashBorder = CAShapeLayer()
        dashBorder.lineWidth = dashWidth
        dashBorder.strokeColor = dashColor.cgColor
        dashBorder.lineDashPattern = [dashLength, betweenDashesSpace] as [NSNumber]
        dashBorder.frame = bounds
        dashBorder.fillColor = nil
        if cornerRadius > 0 {
            dashBorder.path = UIBezierPath(roundedRect: bounds, cornerRadius: cornerRadius).cgPath
        } else {
            dashBorder.path = UIBezierPath(rect: bounds).cgPath
        }
        layer.addSublayer(dashBorder)
        self.dashBorder = dashBorder
    }
}
カテゴリー
iOS Swift

UIImpactFeedbackGeneratorを使う

iOS機器をクリックする時に、「ピクッ」「プクッ」と若干の振動を起こすためのAPI、UIImpactFeedbackGeneratorの使い方。

class ViewController: UIViewController {
  var impactGenerator: UIImpactFeedbackGenerator!
  override func viewDidLoad() {
    super.viewDidLoad()
    impactGenerator = UIImpactFeedbackGenerator(style: .medium)
    impactGenerator.prepare()
  }

  @objc func onTap() {
    impactGenerator.impactOccured()
  }
}
カテゴリー
iOS Swift

iOS & Swift 101(初歩)Part 2

前回のPart 1と同様に、簡単な画面を作成していきます。

class ViewController: UIViewController {
  
  override func viewDidLoad() {
    super.viewDidLoad()
    
    view.backgroundColor = .white
    
    let square = UIView()
    square.backgroundColor = .red
    view.addSubview(square)
    // frame.sizeを指定し
    square.frame.size = CGSize(width: 100, height: 100)
    // 位置情報を指定することも出来る
    square.center = view.center
    
    // UIButtonクラスを使用してみる
    let button = UIButton()
    button.backgroundColor = .green
    button.setTitle("Hello", for: .normal)
    button.setTitleColor(.black, for: .normal)
    // buttonにアクションを追加
    button.addTarget(self, action: #selector(onButtonTapped), for: .touchUpInside)
    view.addSubview(button)
    let buttonSize: CGFloat = 100
    button.frame = CGRect(x: view.bounds.width/2 - buttonSize/2, y: view.bounds.height*3/4 - buttonSize/2, width: buttonSize, height: buttonSize)
  }
  
  // "hello"とprintする簡単なfunction
  // @objcキーワードは、Objective-CというSwiftの前身の言語のAPIを使う場合のもの。button.addTargetを使う場合は必要。
  @objc private func onButtonTapped() {
    print("hello")
  }
}

buttonをクリックすると”hello”とprintされます。

さて、ここで、buttonをクリックすると赤い四角が黄色になる仕組みを組もうとするとどうすればいいでしょうか?

onButtonTapped( )の中にこう書きたいのですが、

@objc private func onButtonTapped() {
    square.backgroundColor = .yellow
}

このままだと「Cannot find ‘square’ in scope」というエラーになります。’square’ という名前のオブジェクトがスコープ内に見つからない、という意味です。

さて、現時点ではsquareはviewDidLoad( )内で定義されています。関数の中で定義された変数(variable, varキーワードで定義)や定数(constant, letキーワードで定義は関数の中でしか扱えません。これを変数や定数の「スコープ」(範囲)といいます。

onButtonTapped( )内で扱えるようにするには、その関数と変数のスコープを合わせます。つまり、同じclass内のトップレベルで定義します。

class ViewController: UIViewController {
  
  let square: UIView = {
    let square = UIView()
    square.backgroundColor = .red
    return square
  }()
  
  override func viewDidLoad() {
    super.viewDidLoad()
    
    view.backgroundColor = .white
    
    view.addSubview(square)
    square.frame.size = CGSize(width: 100, height: 100)
    square.center = view.center
    
    let button = UIButton()
    button.backgroundColor = .green
    button.setTitle("Hello", for: .normal)
    button.setTitleColor(.black, for: .normal)
    button.addTarget(self, action: #selector(onButtonTapped), for: .touchUpInside)
    view.addSubview(button)
    let buttonSize: CGFloat = 100
    button.frame = CGRect(x: view.bounds.width/2 - buttonSize/2, y: view.bounds.height*3/4 - buttonSize/2, width: buttonSize, height: buttonSize)
  }
  
  @objc private func onButtonTapped() {
    square.backgroundColor = .yellow
  }
}

ボタンをクリックすると黄色に変化するプログラムを書けました!

さて、次に、ほんの少しだけ高度な内容についてですが、iOS開発をする上でとても重要なViewControllerのLifecycleの話をします。

例えばiPhoneでは、画面にこのような部分があります。SafeAreaといって、この部分にはアプリに大きく影響する内容のものは表示しない方がいいでしょう。

このpostに書いていますが、view.safeAreaInsets情報はUIViewControllerのlifecycleの中で得られるタイミングが決まっています。viewDidLoad( )がコールされるタイミングではまだ得られておらず、viewWillLayoutSubviews( )で得られます。

viewDidLoad( )はUIViewControllerの生成時に一度だけ呼ばれるため、view.addSubview( )などをコールする場所としては適していますが、実はframeを設定するなどレイアウト関連の作業を実施するには適していません。また、viewWillLayoutSubviews( )はlifecycleの中で状況に応じて何度もコールされるため、view.addSubview( )を実行するには適していません。

つまり、実行する内容によってコールする場所を考慮する必要がある、ということです。

文字にすると難しそうに見えますが、実際にコードを書いて説明します。以下のコードは意図の通りの結果は得られません。

class ViewController: UIViewController {
  // viewWidth、topInsetはcomputed propertyです
  // 何かしらの計算の結果を返すvariableのことをcomputed propertyと呼びます
  var viewWidth: CGFloat {
    return view.bounds.width
  }
  // 
  var topInset: CGFloat {
    view.safeAreaInsets.top
  }
  
  let square: UIView = {
    let square = UIView()
    square.backgroundColor = .red
    return square
  }()
  
  override func viewDidLoad() {
    super.viewDidLoad()
    
    view.backgroundColor = .white
    
    view.addSubview(square)
    square.frame = CGRect(x: 0, y: topInset, width: viewWidth, height: 100)
  }
}

下記のようにviewWillLayoutSubviews( )でコールすると、safeAreaInsetsの情報が反映されます。

class ViewController: UIViewController {
  
  var viewWidth: CGFloat {
    return view.bounds.width
  }
  
  var topInset: CGFloat {
    view.safeAreaInsets.top
  }
  
  let square: UIView = {
    let square = UIView()
    square.backgroundColor = .red
    return square
  }()
  
  override func viewDidLoad() {
    super.viewDidLoad()
    
    view.backgroundColor = .white
    
    view.addSubview(square)
  }
  
  override func viewWillLayoutSubviews() {
    square.frame = CGRect(x: 0, y: topInset, width: viewWidth, height: 100)
  }
}
カテゴリー
iOS Swift

iOS & Swift 101 (初歩) Part 1

最初は取っ付きにくい部分はあまり語らず、出来るだけ直感的に手を動かせるように説明していきます。手を動かして行くと徐々に分かってくると思うからです!

また、後々役に立つため、今回はStoryboardを使用せずに全てコードで書いて行きます。

まずはXcodeのメニューから新しいプロジェクトを作成します。

iOSのApp、を選択し、プロジェクト名(なんでもOK)を入力、InterfaceはStoryboard、LanguageはSwiftを選択してください。

まずはこのまま空のプロジェクトをビルドしてみましょう。ビルド先にSimulatorもしくは実機を選択し、右向きの三角ボタン(プレイボタン)をクリックするか、ショートカットCommand + Rでビルド出来ます。

まっ白なスクリーンが表示されます。

この表示されているものがUIViewControllerです。もう少し正確にいうとViewControllerが標準で持っているviewという「部品」です。

Xcodeの一番左にナビゲーションが表示されているので、ViewControllerという名前のファイルをクリックして開きましょう。ちなみに、この赤く囲っているボタンを押すとナビゲーションを隠したり開いたり出来ます。

ViewController最初は以下のようになっています。「クラスの継承」が最初は分からないかも知れませんが、それは後々説明します。

ちなみに、// の後のテキストは、次に改行されるまで全てコメントとして扱われ、プログラム自体には影響を及ぼしません。プログラムというものは多くの場合、将来の自分が見てもよく分からないことがあります。そのため、どのようなつもり、背景でそう書いたのかを書き残しておくと半年後、一年後の自分に感謝されます ^^ このブログもそのようなきっかけで始めました。。。

import UIKit

// UIViewControllerというクラスを継承(inherit)したViewControllerというクラス
class ViewController: UIViewController {
  // UIViewControllerが持つ標準のfunc
  override func viewDidLoad() {
    super.viewDidLoad()
    
  }
}

ごく簡単に説明すると、iOSのスクリーン上に何かを表示させるためには、最低一つのUIViewController(Root ViewControllerと呼びます)が必要ということです。プロジェクト作成時にはXcodeがViewControllerをひとつ自動で作成してくれます。

viewDidLoadというfunctionは、UIViewControllerが標準で持っている関数ですが、これもまた後々Life Cycle(UIViewControllerが作成されてから破棄されるまで)を解説する時にもう少し詳しく説明します。

実際に手を動かすと徐々に分かってくるので、viewに色をつけてみましょう。viewDidLoad内に以下のように書きます。

class ViewController: UIViewController {
  
  override func viewDidLoad() {
    super.viewDidLoad()
    
    view.backgroundColor = .systemPink
  }
}

Command + Rでビルドしてみると、濃いピンクに変更されました。

iOS開発では、このviewに対して別のviewを追加し画面を組んで行きます。

では実際に別のviewを追加してみましょう。以下のように書きます。

class ViewController: UIViewController {
  
  override func viewDidLoad() {
    super.viewDidLoad()
    
    view.backgroundColor = .systemPink

    // UIViewクラスのインスタンスを作成しanotherViewという名前をつける
    let anotherView = UIView() 
  // 色をつける
    anotherView.backgroundColor = .systemCyan 
  // 親viewにsub viewとして追加
    view.addSubview(anotherView) 
    // 追加しただけだとまだサイズが指定されていないため表示されないので、CGRectを使って指定する
  anotherView.frame = CGRect(x: 0, y: 0, width: 100, height: 100) 
  }
}

Command + Rでビルドすると、左上コーナーにanotherViewが表示されました。

ここではCGRectというクラスを使ってanotherViewのframeを設定しています。frameは親viewに対してどの位置を起点に、どのサイズで表示するか、というものです。

iOSでは左上コーナーが(x: 0, y: 0)という座標でxは左方向へ、yは下方向へプラスの値ということになっています。(ちなみにmacOSの場合は逆で、左下コーナーが(0, 0)です。なぜでしょうね?中の人の派閥が違うんでしょうか??笑)

では、このCyan(シアン)色の四角を、親viewに対して中央に配置してみましょう。いくつかやり方があるのですが、最も簡単な方法は以下です。

class ViewController: UIViewController {
  
  override func viewDidLoad() {
    super.viewDidLoad()
    
    view.backgroundColor = .systemPink
    
    let anotherView = UIView()
    anotherView.backgroundColor = .systemCyan
    view.addSubview(anotherView)
    anotherView.frame = CGRect(x: 0, y: 0, width: 100, height: 100)
    // anotherViewのcenterを親viewのcenterに合わせる
    anotherView.center = view.center
  }
}

ビルドするとCyanの四角が中央に来ました。

別の方法としては、親viewの中のどこに配置するのかを数値で指定するものです。

そのためには親viewのサイズが分かると良さそうです。

先ほどのviewDidLoad内の各ポイントでいくつかの値をprint出力してみたいと思います。

ちなみに、swift標準のprint関数はとても便利です。print関数の引数(arugument)には、コンマ(,)で区切ることで幾つでもオブジェクトをprint出力出来ますし、”文字列”(string)の中に\( )でオブジェクトを囲ってもstringとして出力出来ます。#functionや#lineなどのキーワードを使うことで、どの関数の何行目の出力なのかが分かり、後々デバッグが楽になると思います。ここでは敢えて色々な書き方をしています ^^

class ViewController: UIViewController {
  
  override func viewDidLoad() {
    super.viewDidLoad()
    
    print("\(#function) printing view.bounds: ", view.bounds)
    print("printing view.frame: ", view.frame)
    view.backgroundColor = .systemPink
    
    let anotherView = UIView()
    anotherView.backgroundColor = .systemCyan
    view.addSubview(anotherView)
    anotherView.frame = CGRect(x: 0, y: 0, width: 100, height: 100)
    
    print(#line, " printing anotherView.frame: ", anotherView.frame)
    print("\(#line) printing anotherView.bounds: \(anotherView.bounds)")
    
    anotherView.center = view.center
    
    print("\(#line) frame after centered: ", anotherView.frame)
    print("\(#line) bounds after centered: ", anotherView.bounds)
  }
}

ここで注目したいのは、viewのframeとboundsです。簡単に言うと、frameは親viewの中の位置情報を含んだもの、boundsは自分自身におけるサイズです。これらはiOS開発でしょっちゅう使うので、とても大切です。

ビルドすると、以下のように出力されます。太字はコメントです。

view.boundsは親view自身におけるサイズ情報
viewDidLoad() printing view.bounds:  (0.0, 0.0, 390.0, 844.0)
親viewのframeの位置(起点、origin)は、root viewであるため(0.0, 0.0)
printing view.frame:  (0.0, 0.0, 390.0, 844.0)
centeringする前のanotherViewのframe
24  printing anotherView.frame:  (0.0, 0.0, 100.0, 100.0)
centeringする前のanotherViewのbounds
25 printing anotherView.bounds: (0.0, 0.0, 100.0, 100.0)
centering後のanotherViewのframeは、親view内の位置情報を含みます
29 frame after centered:  (145.0, 372.0, 100.0, 100.0)
centering後のboundsは自分自身における情報なので、変わらず
30 bounds after centered:  (0.0, 0.0, 100.0, 100.0)

では、親viewのサイズが分かったので、それを利用してcenter配置してみます。

x軸の中心値はview.bounds.width/2、y軸の中心値はview.bounds.height/2 でゲット出来ます。anotherViewのサイズは100なので、その半分の値100/2を引くことで、anotherViewのorigin(左上コーナー)とするべき値が得られます。ビルドすると同じ結果が得られます。

class ViewController: UIViewController {
  
  override func viewDidLoad() {
    super.viewDidLoad()
    
    view.backgroundColor = .systemPink
    
    let anotherView = UIView()
    anotherView.backgroundColor = .systemCyan
    view.addSubview(anotherView)
    // Swiftでは文(statement)の途中で改行も可能です。
    anotherView.frame = CGRect(
      x: view.bounds.width/2 - 100/2,
      y: view.bounds.height/2 - 100/2, width: 100, height: 100
    )
  }
}

同じ要領で、anotherViewの中に別のviewを配置してみましょう。

class ViewController: UIViewController {
  
  override func viewDidLoad() {
    super.viewDidLoad()
    
    view.backgroundColor = .systemPink
    
    let anotherView = UIView()
    anotherView.backgroundColor = .systemCyan
    view.addSubview(anotherView)
    anotherView.frame = CGRect(
      x: view.bounds.width/2 - 100/2,
      y: view.bounds.height/2 - 100/2, width: 100, height: 100
    )
    
    let oneMoreView = UIView()
    // .yellowとも書けますが、省略せずに書くとUIColor.yellowです。Swiftは型を推定出来る場合、型を省略して書くことが出来ます。
    oneMoreView.backgroundColor = UIColor.yellow
    // ここではCGFloat型の定数sizeを作成して使っています
    let size: CGFloat = 80
    anotherView.addSubview(oneMoreView)
    oneMoreView.frame = CGRect(x: anotherView.bounds.width/2 - size/2, y: anotherView.bounds.height/2 - size/2, width: size, height: size)
  }
}

黄色のoneMoreViewを円形にしてみましょう。

class ViewController: UIViewController {
  
  override func viewDidLoad() {
    super.viewDidLoad()
    
    view.backgroundColor = .systemPink
    
    let anotherView = UIView()
    anotherView.backgroundColor = .systemCyan
    view.addSubview(anotherView)
    anotherView.frame = CGRect(
      x: view.bounds.width/2 - 100/2,
      y: view.bounds.height/2 - 100/2, width: 100, height: 100
    )
    
    let oneMoreView = UIView()
    oneMoreView.backgroundColor = UIColor.yellow
    let size: CGFloat = 80
    anotherView.addSubview(oneMoreView)
    oneMoreView.frame = CGRect(x: anotherView.bounds.width/2 - size/2, y: anotherView.bounds.height/2 - size/2, width: size, height: size)
   // UIViewの持つlayerというオブジェクトのcornerRadiusというattributeにsize/2を入力します。
    oneMoreView.layer.cornerRadius = size/2
  }
}

UIView以外にもUIButtonやUILabelなどさまざまな部品がUIKitフレームワークには用意されていますが、配置の基本は同じです。

Part 2では変数(や定数)のスコープや、UIViewControllerのLife Cycleを説明するために、もう少しだけ機能を追加した画面を作ってみます。

カテゴリー
JavaScript

Chrome ExtensionのService_WorkerとContent_Script

Service_Worker(Background)とContent_Script(DOM側)の関係が少し分かりにくかったので、書きとめておきます。

以下ではService_Workerをbackground.js、Content_Scriptをcontent.jsとファイル名で呼びます。

content.jsにはDOM(Document Object Model)とのやりとりに関するコード、background.jsにはその他の処理を記述する、と捉えると分かりやすいです。

content.jsとbackground.js間のやりとりはmessagesを介して行います。

background.jsからcontent.jsへは現在アクティブなtab情報を利用してmessagesを送るので、chrome.tabs.sendMessages APIを使います。

// background.js

function setListenerOnMenus() {
  chrome.contextMenus.onClicked.addListener( async (info, tab) => {
    chrome.tabs.sendMessage(tab.id, {
      // some message. can be blank
      something: "some message",
      somethingElse: "another message"
    }, (response) => {
      // receiver of the message (content.js) can return a respond
      // in a callback
      // background.js can respond to that response here...
      let context = response.context;
      let url = response.url;
      // do something with it!...
    }
  }
}
// content.js
chrome.runtime.onMessage.addListener( (request, sender, sendResponse) => {
  // request contains messages sent from background.js. Can retrieve as below...
  let something = request.something;
  let somethingElse = request.somethingElse;
  
  // also, content.js can interact/manipulate DOM element and communicate it back to background.js
  let url = window.location.href;
  let context = window.getSelection().anchorNode.data;
  // can communicate back in the callback below...
  sendResponse({
    context: context,
    url: url
  });
}

background.jsにはonStartup listenerを追加することで、extension使用時に起動するようになります。

// background.js

chrome.runtime.onStartup.addListener(() => {
  setup();
});