Create UIButtons with dynamic font size but all share same font size in UIStackView - swift

I am using UIStackView and adding three buttons to it. I want it so that the button with the most text (B1) will be auto resized to fit the width and the other buttons will share the same font size as B1.
#IBOutlet weak var stackView: UIStackView!
var btnTitles = [String]()
btnTitles.append("Practice Exams")
btnTitles.append("Test Taking Tips")
btnTitles.append("About")
createButtons(buttonTitles: btnTitles)
var min = CGFloat(Int.max) // keep track of min font
func createButtons(buttonTitles: [String]) {
var Buttons = [UIButton]()
for title in buttonTitles {
let button = makeButtonWithText(text: title)
// set the font to dynamically size
button.titleLabel!.numberOfLines = 1
button.titleLabel!.adjustsFontSizeToFitWidth = true
button.titleLabel!.baselineAdjustment = .alignCenters // I think it keeps it centered vertically
button.contentEdgeInsets = UIEdgeInsetsMake(5, 10, 5, 10); // set margins
if (button.titleLabel?.font.pointSize)! < min {
min = (button.titleLabel?.font.pointSize)! // to get the minimum font size of any of the buttons
}
stackView.addArrangedSubview(button)
Buttons.append(button)
}
}
func makeButtonWithText(text:String) -> UIButton {
var myButton = UIButton(type: UIButtonType.system)
//Set a frame for the button. Ignored in AutoLayout/ Stack Views
myButton.frame = CGRect(x: 30, y: 30, width: 150, height: 100)
// background color - light blue
myButton.backgroundColor = UIColor(red: 0.255, green: 0.561, blue: 0.847, alpha: 1)
//State dependent properties title and title color
myButton.setTitle(text, for: UIControlState.normal)
myButton.setTitleColor(UIColor.white, for: UIControlState.normal)
// set the font to dynamically size
myButton.titleLabel!.font = myButton.titleLabel!.font.withSize(70)
myButton.contentHorizontalAlignment = .center // align center
return myButton
}
I wanted to find the minimum font size and then set all the buttons to the minimum in viewDidAppear button the font prints as 70 for all of them even though they clearly appear different sizes (see image)
override func viewDidAppear(_ animated: Bool) {
print("viewDidAppear")
let button = stackView.arrangedSubviews[0] as! UIButton
print(button.titleLabel?.font.pointSize)
let button1 = stackView.arrangedSubviews[1] as! UIButton
print(button1.titleLabel?.font.pointSize)
let button2 = stackView.arrangedSubviews[2] as! UIButton
print(button2.titleLabel?.font.pointSize)
}
image

You can try playing around with this func to return the scaled-font-size of a label:
func actualFontSize(for aLabel: UILabel) -> CGFloat {
// label must have text, must have .minimumScaleFactor and must have .adjustsFontSizeToFitWidth == true
guard let str = aLabel.text,
aLabel.minimumScaleFactor > 0.0,
aLabel.adjustsFontSizeToFitWidth
else { return aLabel.font.pointSize }
let attributes = [NSAttributedString.Key.font : aLabel.font]
let attStr = NSMutableAttributedString(string:str, attributes:attributes as [NSAttributedString.Key : Any])
let context = NSStringDrawingContext()
context.minimumScaleFactor = aLabel.minimumScaleFactor
_ = attStr.boundingRect(with: aLabel.bounds.size, options: .usesLineFragmentOrigin, context: context)
return aLabel.font.pointSize * context.actualScaleFactor
}
On viewDidAppear() you would loop through the buttons, getting the smallest actual font size, then set the font size for each button to that value.
It will take some experimentation... For one thing, I've noticed in the past that font-sizes can get rounded - so setting a label's font point size to 20.123456789 won't necessarily give you that exact point size. Also, since this changes the actual font size assigned to the labels, you'll need to do some resetting if you change the button title dynamically. Probably also need to account for button frame changes (such as with device rotation, etc).
But... here is a quick test that you can run to see the approach:
class TestViewController: UIViewController {
let stackView: UIStackView = {
let v = UIStackView()
v.translatesAutoresizingMaskIntoConstraints = false
v.axis = .vertical
v.alignment = .center
v.distribution = .fillEqually
v.spacing = 8
return v
}()
var btnTitles = [String]()
var theButtons = [UIButton]()
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
fixButtonFonts()
}
func setupUI() -> Void {
view.addSubview(stackView)
NSLayoutConstraint.activate([
stackView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 40),
stackView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 40),
stackView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -40),
])
btnTitles.append("Practice Exams")
btnTitles.append("Test Taking Tips")
btnTitles.append("About")
createButtons(buttonTitles: btnTitles)
}
func fixButtonFonts() -> Void {
var minActual = CGFloat(70)
// get the smallest actual font size
theButtons.forEach { btn in
if let lbl = btn.titleLabel {
let act = actualFontSize(for: lbl)
// for debugging
//print("actual font size: \(act)")
minActual = Swift.min(minActual, act)
}
}
// set font size for each button
theButtons.forEach { btn in
if let lbl = btn.titleLabel {
lbl.font = lbl.font.withSize(minActual)
}
}
}
func createButtons(buttonTitles: [String]) {
for title in buttonTitles {
let button = makeButtonWithText(text: title)
// set the font to dynamically size
button.titleLabel!.numberOfLines = 1
button.titleLabel!.adjustsFontSizeToFitWidth = true
// .minimumScaleFactor is required
button.titleLabel!.minimumScaleFactor = 0.05
button.titleLabel!.baselineAdjustment = .alignCenters // I think it keeps it centered vertically
button.contentEdgeInsets = UIEdgeInsets(top: 5, left: 10, bottom: 5, right: 10); // set margins
stackView.addArrangedSubview(button)
theButtons.append(button)
}
}
func makeButtonWithText(text:String) -> UIButton {
let myButton = UIButton(type: UIButton.ButtonType.system)
//Set a frame for the button. Ignored in AutoLayout/ Stack Views
myButton.frame = CGRect(x: 30, y: 30, width: 150, height: 100)
// background color - light blue
myButton.backgroundColor = UIColor(red: 0.255, green: 0.561, blue: 0.847, alpha: 1)
//State dependent properties title and title color
myButton.setTitle(text, for: UIControl.State.normal)
myButton.setTitleColor(UIColor.white, for: UIControl.State.normal)
// set the font to dynamically size
myButton.titleLabel!.font = myButton.titleLabel!.font.withSize(70)
myButton.contentHorizontalAlignment = .center // align center
return myButton
}
func actualFontSize(for aLabel: UILabel) -> CGFloat {
// label must have text, must have .minimumScaleFactor and must have .adjustsFontSizeToFitWidth == true
guard let str = aLabel.text,
aLabel.minimumScaleFactor > 0.0,
aLabel.adjustsFontSizeToFitWidth
else { return aLabel.font.pointSize }
let attributes = [NSAttributedString.Key.font : aLabel.font]
let attStr = NSMutableAttributedString(string:str, attributes:attributes as [NSAttributedString.Key : Any])
let context = NSStringDrawingContext()
context.minimumScaleFactor = aLabel.minimumScaleFactor
_ = attStr.boundingRect(with: aLabel.bounds.size, options: .usesLineFragmentOrigin, context: context)
return aLabel.font.pointSize * context.actualScaleFactor
}
}
Result:

Related

Search bar with corner radius in swift

I want to create a view like the above image.it has a search bar with corner radius.but when i am trying to create, i am unable to make the search bar with corner radius.also i am unable to make the text field of the search bar with corner radius. i have writtenall my code in viewDidAppear method. It is ok or i have to write it in viewWillLayourSubview. so that i will be able to make the exact
same search bar like this image. also i want the seach icon to be placed slightly right.
My code is:
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(true)
for subView in searchBar.subviews {
for subsubView in subView.subviews {
if let textField = subsubView as? UITextField {
var bounds: CGRect
var placeHolder = NSMutableAttributedString()
let Name = "Search"
placeHolder = NSMutableAttributedString(string:Name, attributes: [NSAttributedString.Key.font:UIFont(name: "Helvetica", size: 15.0)!])
placeHolder.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.gray, range:NSRange(location:0,length:Name.count))
textField.attributedPlaceholder = placeHolder
if let leftView = textField.leftView as? UIImageView {
leftView.image = leftView.image?.withRenderingMode(.alwaysTemplate)
leftView.frame.size.width = 15.0
leftView.frame.size.height = 15.0
leftView.tintColor = UIColor.gray
}
textField.layer.cornerRadius = 50.0
bounds = textField.frame
bounds.size.width = searchBar.frame.width
bounds.size.height = searchBar.frame.height
textField.bounds = bounds
textField.borderStyle = UITextField.BorderStyle.roundedRect
searchBar.backgroundImage = UIImage()
textField.backgroundColor = UIColor.lightGray.withAlphaComponent(0.2)
searchBar.searchTextPositionAdjustment = UIOffset(horizontal: 5, vertical: 0)
}
}
}
}*
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(true)
for subView in searchBar.subviews {
if !subView.subviews.contains(where: { $0 as? UITextField != nil }) { continue }
guard let textField = subView.subviews.first(where: { $0 as? UITextField != nil }) as? UITextField else { return }
let placeholder = NSMutableAttributedString(
string: "Search",
attributes: [.font: UIFont(name: "Helvetica", size: 15.0)!,
.foregroundColor: UIColor.gray
])
textField.attributedPlaceholder = placeholder
textField.borderStyle = UITextField.BorderStyle.roundedRect
textField.layer.cornerRadius = textField.frame.size.height / 2
textField.layer.masksToBounds = true
textField.textColor = .white
textField.backgroundColor = .lightGray
}
searchBar.barTintColor = .white
searchBar.backgroundColor = .white
searchBar.searchTextPositionAdjustment = UIOffset(horizontal: 5, vertical: 0)
}
Doesn't look exactly like in the image that you linked, but actually fits better into the Apple design and works better than the code that you wrote.
For anything more sophisticated, I would advise to create a custom UISearchBar subclass.
Be aware of Apple's Human Interface Guidelines, so anything too crazy / different from default might not be accepted in the AppStore.

NSGridView difficulties

I'm using an NSGridView in the settings panel for my macOS app. I set it up like this:
class GeneralViewController: RootViewController {
private var gridView: NSGridView?
override func loadView() {
super.loadView()
let restaurantLabel = NSTextField()
restaurantLabel.stringValue = "Restaurant"
let restaurantButton = NSPopUpButton()
restaurantButton.addItems(withTitles: ["A", "B", "C"])
let updatesLabel = NSTextField()
updatesLabel.stringValue = "Updates"
updatesLabel.isEditable = false
updatesLabel.isBordered = false
updatesLabel.isBezeled = false
let updatesButton = NSButton(checkboxWithTitle: "Automatically pull in updates from WordPress", target: nil, action: nil)
let empty = NSGridCell.emptyContentView
gridView = NSGridView(views: [
[restaurantLabel, restaurantButton],
[updatesLabel, updatesButton]
])
gridView?.wantsLayer = true
gridView?.layer?.backgroundColor = NSColor.red.cgColor
gridView?.column(at: 0).xPlacement = .trailing
gridView?.rowAlignment = .firstBaseline
gridView?.setContentHuggingPriority(NSLayoutConstraint.Priority(rawValue: 600), for: .horizontal)
gridView?.setContentHuggingPriority(NSLayoutConstraint.Priority(rawValue: 600), for: .vertical)
view.addSubview(gridView!)
}
override func viewDidLayout() {
super.viewDidLayout()
gridView?.frame = NSRect(x: 0, y: 0, width: view.frame.size.width, height: view.frame.size.height)
}
}
Now, when I run this, the NSGridView fills up the whole view, but the checkbox is really off. As you can see in the image.
Also, I'd love for the content to not fill the whole cell, making it all look a tad more centered.
How can I solve this?
If you change the row alignment to .lastBaseline it will fix your issue of the vertical alignment of the NSButton and the NSTextField. If you want more spacing (I'm guessing that's what you mean with "I'd love for the content to not fill the whole cell"), you can use the columnSpacing and rowSpacing properties of the NSGridView. If you then also add instances of NSGridCell.emptyContentView around your "real" content, you should be able to achieve the following effect.
This is new code after the changes I suggested:
class GeneralViewController: RootViewController {
private var gridView: NSGridView?
override func loadView() {
super.loadView()
let restaurantLabel = NSTextField()
restaurantLabel.stringValue = "Restaurant"
let restaurantButton = NSPopUpButton()
restaurantButton.addItems(withTitles: ["A", "B", "C"])
let updatesLabel = NSTextField()
updatesLabel.stringValue = "Updates"
updatesLabel.isEditable = false
updatesLabel.isBordered = false
updatesLabel.isBezeled = false
let updatesButton = NSButton(checkboxWithTitle: "Automatically pull in updates from WordPress", target: nil, action: nil)
let empty = NSGridCell.emptyContentView
gridView = NSGridView(views: [
[empty],
[empty, restaurantLabel, restaurantButton, empty],
[empty, updatesLabel, updatesButton, empty],
[empty],
[empty]
])
gridView?.wantsLayer = true
gridView?.layer?.backgroundColor = NSColor.red.cgColor
gridView?.column(at: 0).xPlacement = .trailing
gridView?.rowAlignment = .lastBaseline
gridView?.columnSpacing = 20
gridView?.rowSpacing = 20
gridView?.setContentHuggingPriority(NSLayoutConstraint.Priority(rawValue: 600), for: .horizontal)
gridView?.setContentHuggingPriority(NSLayoutConstraint.Priority(rawValue: 600), for: .vertical)
view.addSubview(gridView!)
}
override func viewDidLayout() {
super.viewDidLayout()
gridView?.frame = NSRect(x: 0, y: 0, width: view.frame.size.width, height: view.frame.size.height)
}
}

Button becomes inactive in programmatic dynamic stackView (Swift)

I'm trying to implement a programmatic version of the Dynamic Stack View in Apple's Auto Layout Cookbook. An "Add Item" button is supposed to add new views to a vertical stackView, including a delete button to remove each view. My programmatic code works fine for 1 touch of the "Add Item" button, but then that button becomes inactive. As a result, I can only add 1 item to the stackView. If I used the delete button, the "Add Item" becomes active again. I've included an animated gif to illustrate.
I'm posting both my Programmatic code (which has the problem) and below that the original storyboard-based code (which works fine). I've tried putting a debug breakpoint at the addEntry func, but that didn't help. -Thanks
Programmatic Code ("Add Item" button only works once):
import UIKit
class CodeDynamStackVC: UIViewController {
// MARK: Properties
var scrollView = UIScrollView()
var stackView = UIStackView()
var button = UIButton()
// MARK: UIViewController
override func viewDidLoad() {
super.viewDidLoad()
// Set up the scrollview
let insets = UIEdgeInsets(top: 20, left: 0.0, bottom: 0.0, right: 0.0)
scrollView.contentInset = insets
scrollView.scrollIndicatorInsets = insets
setupInitialVertStackView()
}
//setup initial button inside vertical stackView
func setupInitialVertStackView() {
// make inital "Add Item" button
button = UIButton(type: .system)
button.setTitle("Add Item", for: .normal)
button.setTitleColor(UIColor.blue, for: .normal)
button.addTarget(self, action: #selector(addEntry), for: .touchUpInside)
//enclose button in a vertical stackView
stackView.addArrangedSubview(button)
stackView.axis = .vertical
stackView.alignment = .fill
stackView.distribution = .equalSpacing
stackView.spacing = 5
stackView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(stackView)
let viewsDictionary = ["v0":stackView]
let stackView_H = NSLayoutConstraint.constraints(withVisualFormat: "H:|[v0]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewsDictionary)
let stackView_V = NSLayoutConstraint.constraints(withVisualFormat: "V:|-20-[v0(25)]|", options: NSLayoutFormatOptions(rawValue:0), metrics: nil, views: viewsDictionary)
view.addConstraints(stackView_H)
view.addConstraints(stackView_V)
}
// MARK: Interface Builder actions
func addEntry() {
guard let addButtonContainerView = stackView.arrangedSubviews.last else { fatalError("Expected at least one arranged view in the stack view.") }
let nextEntryIndex = stackView.arrangedSubviews.count - 1
let offset = CGPoint(x: scrollView.contentOffset.x, y: scrollView.contentOffset.y + addButtonContainerView.bounds.size.height)
let newEntryView = createEntryView()
newEntryView.isHidden = true
stackView.insertArrangedSubview(newEntryView, at: nextEntryIndex)
UIView.animate(withDuration: 0.25, animations: {
newEntryView.isHidden = false
self.scrollView.contentOffset = offset
})
}
func deleteStackView(_ sender: UIButton) {
guard let entryView = sender.superview else { return }
UIView.animate(withDuration: 0.25, animations: {
entryView.isHidden = true
}, completion: { _ in
entryView.removeFromSuperview()
})
}
// MARK: Convenience
/// Creates a horizontal stackView entry to place within the parent vertical stackView
fileprivate func createEntryView() -> UIView {
let date = DateFormatter.localizedString(from: Date(), dateStyle: .short, timeStyle: .none)
let number = UUID().uuidString
let stack = UIStackView()
stack.axis = .horizontal
stack.alignment = .center
stack.distribution = .fill
stack.spacing = 8
let dateLabel = UILabel()
dateLabel.text = date
dateLabel.font = UIFont.preferredFont(forTextStyle: UIFontTextStyle.body)
let numberLabel = UILabel()
numberLabel.text = number
numberLabel.font = UIFont.preferredFont(forTextStyle: UIFontTextStyle.caption2)
numberLabel.setContentHuggingPriority(UILayoutPriorityDefaultLow - 1.0, for: .horizontal)
numberLabel.setContentCompressionResistancePriority(UILayoutPriorityDefaultHigh - 1.0, for: .horizontal)
let deleteButton = UIButton(type: .roundedRect)
deleteButton.setTitle("Del", for: UIControlState())
deleteButton.addTarget(self, action: #selector(DynamStackVC.deleteStackView(_:)), for: .touchUpInside)
stack.addArrangedSubview(dateLabel)
stack.addArrangedSubview(numberLabel)
stack.addArrangedSubview(deleteButton)
return stack
}
}
Storyboard-based Code ("Add Item" button always works)
import UIKit
class DynamStackVC: UIViewController {
// MARK: Properties
#IBOutlet weak var scrollView: UIScrollView!
#IBOutlet weak var stackView: UIStackView!
// MARK: UIViewController
override func viewDidLoad() {
super.viewDidLoad()
// Set up the scrollview.
let insets = UIEdgeInsets(top: 20, left: 0.0, bottom: 0.0, right: 0.0)
scrollView.contentInset = insets
scrollView.scrollIndicatorInsets = insets
}
// MARK: Interface Builder actions
#IBAction func addEntry(_: AnyObject) {
guard let addButtonContainerView = stackView.arrangedSubviews.last else { fatalError("Expected at least one arranged view in the stack view.") }
let nextEntryIndex = stackView.arrangedSubviews.count - 1
let offset = CGPoint(x: scrollView.contentOffset.x, y: scrollView.contentOffset.y + addButtonContainerView.bounds.size.height)
let newEntryView = createEntryView()
newEntryView.isHidden = true
stackView.insertArrangedSubview(newEntryView, at: nextEntryIndex)
UIView.animate(withDuration: 0.25, animations: {
newEntryView.isHidden = false
self.scrollView.contentOffset = offset
})
}
func deleteStackView(_ sender: UIButton) {
guard let entryView = sender.superview else { return }
UIView.animate(withDuration: 0.25, animations: {
entryView.isHidden = true
}, completion: { _ in
entryView.removeFromSuperview()
})
}
// MARK: Convenience
/// Creates a horizontal stack view entry to place within the parent `stackView`.
fileprivate func createEntryView() -> UIView {
let date = DateFormatter.localizedString(from: Date(), dateStyle: .short, timeStyle: .none)
let number = UUID().uuidString
let stack = UIStackView()
stack.axis = .horizontal
stack.alignment = .center
stack.distribution = .fillProportionally
stack.spacing = 8
let dateLabel = UILabel()
dateLabel.text = date
dateLabel.font = UIFont.preferredFont(forTextStyle: UIFontTextStyle.body)
let numberLabel = UILabel()
numberLabel.text = number
numberLabel.font = UIFont.preferredFont(forTextStyle: UIFontTextStyle.caption2)
numberLabel.setContentHuggingPriority(UILayoutPriorityDefaultLow - 1.0, for: .horizontal)
numberLabel.setContentCompressionResistancePriority(UILayoutPriorityDefaultHigh - 1.0, for: .horizontal)
let deleteButton = UIButton(type: .roundedRect)
deleteButton.setTitle("Del", for: UIControlState())
deleteButton.addTarget(self, action: #selector(DynamStackVC.deleteStackView(_:)), for: .touchUpInside)
stack.addArrangedSubview(dateLabel)
stack.addArrangedSubview(numberLabel)
stack.addArrangedSubview(deleteButton)
return stack
}
}
I figured it out by putting background colors on all buttons and labels within the dynamic stackView. As you can see in the new animated gif, the cyan color of the "Add Item" button disappears after the first button press. To confirm, I doubled the original height of the button (i.e., from (25) to (50) at the left in the gif), which then allowed for two button pressed before it no longer worked and the cyan background disappeared. This taught me a lot about how the dynamic stackView works, and I hope it will help someone else.

textview shakes when resizing view

I'm resizing the view that a textview belongs to and the text shakes when the view either gets bigger or gets smaller.
Declaration of said text view:
lazy var textview: UITextView = {
let textView = UITextView()
textView.text = ""
textView.font = .systemFont(ofSize: 12, weight: UIFontWeightMedium)
textView.isScrollEnabled = false
textView.isEditable = false
textView.isSelectable = true
textView.isUserInteractionEnabled = true
textView.translatesAutoresizingMaskIntoConstraints = false
textView.textAlignment = .center
textView.textColor = .lightGray
textView.dataDetectorTypes = .link
return textView
}()
I'm resizing the view that it's in to fit the full screen like this
if let window = UIApplication.shared.keyWindow {
let statusBarHeight = UIApplication.shared.statusBarFrame.size.height
UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveLinear, animations: {
self.frame = CGRect(x: 0, y: statusBarHeight, width: window.frame.width, height: window.frame.height - statusBarHeight)
self.layer.cornerRadius = 0
self.layoutIfNeeded()
}, completion: nil)
}
Upon doing so, the view expands perfectly but the textviews text does a bounce effect that makes the animation look extremely unprofessional... any advice?
Edit: It seems like when I remove the center text alignment option it works fine. How do I make it work with the text center aligned?
edit: I took another look at this and attempted to use the technique based in UIScrollView animation of height and contentOffset "jumps" content from bottom.
Here's a minimal working example with text view with centered text alignment which is working for me!
I'd recommend managing animations either to be all constraint based, or all frame based. I attempted a version where the animation is driven by updating the container view frame but it was starting to take too long to left it at this constraint based approach.
Hope this points you in the right direction :)
import UIKit
class ViewController: UIViewController {
lazy var textView: UITextView = {
let textView = UITextView()
textView.text = "testing text view"
textView.textAlignment = .center
textView.translatesAutoresizingMaskIntoConstraints = false
return textView
}()
lazy var containerView: UIView = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
var widthConstraint: NSLayoutConstraint!
var topAnchor: NSLayoutConstraint!
override func viewDidLoad() {
view.backgroundColor = .groupTableViewBackground
// add container view and constraints
view.addSubview(containerView)
containerView.frame = view.bounds.insetBy(dx: 100, dy: 200)
containerView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
containerView.heightAnchor.constraint(equalToConstant: 100).isActive = true
// keep reference to topAnchor and width as properties to animate
topAnchor = containerView.topAnchor.constraint(lessThanOrEqualTo: view.topAnchor, constant: 100)
widthConstraint = containerView.widthAnchor.constraint(equalToConstant: 300)
topAnchor.isActive = true
widthConstraint.isActive = true
// add text view to container view and set constraints
containerView.addSubview(textView)
textView.leftAnchor.constraint(equalTo: containerView.leftAnchor).isActive = true
textView.rightAnchor.constraint(equalTo: containerView.rightAnchor).isActive = true
textView.topAnchor.constraint(equalTo: containerView.topAnchor).isActive = true
textView.bottomAnchor.constraint(equalTo: containerView.bottomAnchor).isActive = true
}
#IBAction func toggleResize(_ sender: UIButton) {
sender.isSelected = !sender.isSelected
view.layoutIfNeeded()
widthConstraint.constant = sender.isSelected ? view.bounds.width : 300
topAnchor.constant = sender.isSelected ? 20 : 100
// caculate the textView content offset for starting position based on
// expected end position at end of the animation
let xOffset = (textView.bounds.width - widthConstraint.constant) / 2
textView.contentOffset = CGPoint(x: -xOffset, y: textView.contentOffset.y)
UIView.animate(withDuration: 1) {
self.view.layoutIfNeeded()
}
}
}

How do I change the colors of 9 objects after the right object is pressed?

I have 9 buttons/squares that each have a different color. When the right color is pressed, all the buttons should switch colors. For example: if I press the red square, then the colors of the squares should change so that another square becomes red. So far I got
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
var Ctimer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: "colors", userInfo: nil, repeats: true)
B1.backgroundColor = UIColor.blueColor()
B2.backgroundColor = UIColor.greenColor()
B3.backgroundColor = UIColor.cyanColor()
B4.backgroundColor = UIColor.purpleColor()
B5.backgroundColor = UIColor.redColor()
B6.backgroundColor = UIColor.brownColor()
B7.backgroundColor = UIColor.yellowColor()
B8.backgroundColor = UIColor.orangeColor()
B9.backgroundColor = UIColor.magentaColor()
}
func colors() {
var red = CGFloat(drand48())
var green = CGFloat(drand48())
var blue = CGFloat(drand48())
self.view.backgroundColor = UIColor(red: red, green: green, blue: blue, alpha: 1.0)
}
func changeButtonColors(){
var rand = arc4random_uniform(10)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
B1, B2, etc are buttons. I am confused as to how I can randomize the change of colors without having to hardcode every possible alternative.
I'm not sure I fully understand what your trying to do, I have implemented some code below which creates 9 buttons all of a different colour and on tap assigns the tapped button a random colour out of the array, then finds the other button which has that new colour and replaces it with the previous one. So they are always unique... is that what you wanted?
Either way, the code below should help you to acheive what you need, it has an array of colors and methods of accessing them via the index or selecting random ones, gesture recognition on the buttons.
class ViewController: UIViewController {
let spacing = 10
let buttonCount = 9
let buttonSize = 40
var buttons = [UIButton]()
let colors = [
UIColor.blueColor(),
UIColor.blackColor(),
UIColor.yellowColor(),
UIColor.redColor(),
UIColor.orangeColor(),
UIColor.greenColor(),
UIColor.purpleColor(),
UIColor.magentaColor(),
UIColor.cyanColor()
]
func selectRandomColor() -> UIColor {
let randomIndex = Int(arc4random_uniform(UInt32(colors.count)))
return colors[randomIndex]
}
func buttonTapped(gestureRecognizer: UIGestureRecognizer) {
let sender = gestureRecognizer.view as! UIButton
let currentColor = sender.backgroundColor
var randColor = selectRandomColor()
while randColor === currentColor {
randColor = selectRandomColor()
}
sender.backgroundColor = randColor
for button in buttons where sender !== button {
if button.backgroundColor == randColor {
button.backgroundColor = currentColor
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
for num in 0..<buttonCount {
let xPostion = (buttonSize * num) + (spacing * num)
let button = UIButton(frame: CGRect(x: xPostion, y: 40, width: buttonSize, height: buttonSize))
button.backgroundColor = colors[num]
let tapRecognisor = UITapGestureRecognizer(target: self, action: #selector(self.buttonTapped(_:)))
button.addGestureRecognizer(tapRecognisor)
buttons.append(button)
view.addSubview(button)
}
}
}
you can create the array of color object and pass it accordingly when you press. To apply random color on buttons just generate array of numbers between color array count and apply on accordingly.