Slava Slava - 7 months ago 40
Swift Question

Add objective c code to swift file

I need to add somehow the following objective-c code to AppDelegate.swift file into the function.

// Define some colors.
UIColor *darkGray = [UIColor darkGrayColor];
UIColor *lightGray = [UIColor lightGrayColor];

// Navigation bar background.
[[UINavigationBar appearance] setBarTintColor:darkGray];
[[UINavigationBar appearance] setTintColor:lightGray];

// Color of typed text in the search bar.
NSDictionary *searchBarTextAttributes = @{
NSForegroundColorAttributeName: lightGray,
NSFontAttributeName : [UIFont systemFontOfSize:[UIFont systemFontSize]]
};
[UITextField appearanceWhenContainedInInstancesOfClasses:@[[UISearchBar class]]]
.defaultTextAttributes = searchBarTextAttributes;

// Color of the placeholder text in the search bar prior to text entry.
NSDictionary *placeholderAttributes = @{
NSForegroundColorAttributeName: lightGray,
NSFontAttributeName : [UIFont systemFontOfSize:[UIFont systemFontSize]]
};

// Color of the default search text.
// NOTE: In a production scenario, "Search" would be a localized string.
NSAttributedString *attributedPlaceholder =
[[NSAttributedString alloc] initWithString:@"Search"
attributes:placeholderAttributes];
[UITextField appearanceWhenContainedInInstancesOfClasses:@[[UISearchBar class]]]
.attributedPlaceholder = attributedPlaceholder;


What is the best solution for it? Should I just create Objective-C file or header?

Answer

This is rough translation to Swift...no tested.

// Define some colors.
var darkGray: UIColor = UIColor.darkGrayColor()
var lightGray: UIColor = UIColor.lightGrayColor()
// Navigation bar background.
UINavigationBar.appearance().barTintColor = darkGray
UINavigationBar.appearance().tintColor = lightGray
    // Color of typed text in the search bar.
var searchBarTextAttributes: [NSObject : AnyObject] = [NSForegroundColorAttributeName: lightGray, NSFontAttributeName: UIFont.systemFontOfSize(UIFont.systemFontSize())]
UITextField.appearanceWhenContainedInInstancesOfClasses([UISearchBar.self]).defaultTextAttributes = searchBarTextAttributes
    // Color of the placeholder text in the search bar prior to text entry.
var placeholderAttributes: [NSObject : AnyObject] = [NSForegroundColorAttributeName: lightGray, NSFontAttributeName: UIFont.systemFontOfSize(UIFont.systemFontSize())]

   // Color of the default search text.
    // NOTE: In a production scenario, "Search" would be a localized string.
var attributedPlaceholder: NSAttributedString = NSAttributedString(string: "Search", attributes: placeholderAttributes)
UITextField.appearanceWhenContainedInInstancesOfClasses([UISearchBar.self]).attributedPlaceholder = attributedPlaceholder
Comments