반응형

iOS 15에서 네비게이션 바가  검정색으로 변화되는 현상을 발견하였다.

시뮬레이터에 돌려서 보았을 때는 그런 증상이 있었고,

이 증상을 보자마자 단말기에서도 동일 증상이 있는지 확인 하였으나 발생되지 않았다.

뭐지 하면서 우선 관련되 내용을 찾아보았다.

https://developer.apple.com/forums/thread/683590

 

iOS 15 B2 UINavigationBar Appearan… | Apple Developer Forums

Hey All! When transitioning my app to use the nav bar appearance (introduce in ios13, but required to make navigation bar colors / backgrounds in io15) i believe i had everything all changed over and working ! in iOS 15 b2 it seems when changing navbar bac

developer.apple.com

 

해당 내용을 보고 추가해주었더니 정상 작동을 하였다.

if #available(iOS 15, *) {
    let barAppearance = UINavigationBarAppearance()
    barAppearance.backgroundColor = .white
    navigationItem.standardAppearance = barAppearance
    navigationItem.scrollEdgeAppearance = barAppearance
}

 

반응형
반응형

ituncesconnect 에 빌드된 파일을 업로드 할 때

수출규정 관련 문서가 누락되었다고 느낌표가 뜨는 경우가 있다.

 

이것은 어플에 암호화 기능이 있으면 반드시 추가를 해줘야하는 문서 인것같다.

필자는 암호화 기능을 써본적이 없다.

그래서 항상 무시를 했었다. 무시를 해도 암호화 기능만 없다면 정상적으로 처리가 되었다.

 

느낌표가 나오는 게 찝찝하다면, 아래와 같이 해도 될 것 같다.

xcode에서 info.plist에서 추가한다.

<key>ITSAppUsesNonExemptEncryption</key> <No>

 

 

추가 했을 경우 메세지가 사라졌다.

반응형
반응형

https://github.com/ADVTOOLS/ADVTrustStore

 

ADVTOOLS/ADVTrustStore

ADVTrustStore is a simple management script to import/list/remove CA certificates to the iOS simulator. It is working for iOS 5 and iOS 6. - ADVTOOLS/ADVTrustStore

github.com

보안 관련하여 인증서를 회사에서 받았다. 이후 Xcode 시뮬레이터에서 인터넷이 되지 않았다.

결론은 시뮬레이터에도 동일한 인증서를 넣어주어야 한다.

 

위 사이트를 들어가보면 해결 방안이 잘 나와있다. 

참고로 필자도 위 사이트를 보고 해결하였다.

항상 그랬듯 찾는 시간이 오래 걸리지 해결은 쉬웠다.

 

iosCerTrustManager.py 를 다운 받는다.

$ ./iosCertTrustManager.py --help

$ ./iosCertTrustManager.py -a fileName.pem

subject= CN = goodgods.tistory.com <- 인증서

 

Import certificate to iPhone 11 Pro Max v13.3 [y/N] y

Importing to /Users/comms/Library/Developer/CoreSimulator/Devices/70B8D234-8CD5-43F7-8915-80378BB7116C/data/Library/Keychains/TrustStore.sqlite3

  Certificate added

Import certificate to iPhone 11 v13.3 [y/N] y

Importing to /Users/comms/Library/Developer/CoreSimulator/Devices/8BE1EF1C-42D4-4C17-BC25-685EBB0726C2/data/Library/Keychains/TrustStore.sqlite3

  Certificate added 

 

 

xcode 12에서 안된다면...

1. 파일경로에 한글이 포함된 폴더가 존재하면 안되는 것 같다.

2. 원하는 시뮬레이터를 실행시킨 후에 해보자.

반응형
반응형

실행 오류
상세오류

 

singing 이 맞지 않아서 생긴 문제라고 한다.

signing 부분을 수동으로 관리하고 있었는데, 이부분을 auto로 했더니 잘된다.

 

다만 이렇게 되면 실배포할때는 또 안될 것 같다는 생각이든다.

그럴땐 다시 수동으로 해줘야할 것같은데, Target을 복사해서 singing 부분만 바꿔서 사용해야할지 고민을 해봐야할 것 같다.

 

 

반응형
반응형

let message = "abcdefg\n1234567\n가나다라마바사\nABCDEFG"

let line = message.reduce(into: 0) { (count,letter) in

    if letter == "\n" {

        count += 1

    }

}

 

print(line)

 

https://stackoverflow.com/questions/46490920/count-the-number-of-lines-in-a-swift-string

반응형

'Programming > Swift' 카테고리의 다른 글

[swift5] 시뮬레이터에 인증서 넣기  (0) 2020.02.25
[Swift5] 아이폰 연결시 에러  (0) 2020.02.03
xcode git 연동 문제  (0) 2020.01.16
[swift] slide animation  (0) 2019.11.21
[cocoaPods] 프로젝트 만들어 보기  (0) 2019.10.22
반응형

pc를 재설치하고 Xcode에 git 셋팅 후 작업을 해보았다.

그러나 아래와 같은 메세지를 보여주며 작동이 되지 않는다.

 

이런 경우 Fix 버튼을 눌러서 Author Name, Author Email 값을 넣어준다.

끝.

반응형
반응형

case 1.

let transition = CATransition()

transition.type = CATransitionType.push

transition.subtype = CATransitionSubtype.fromLeft

memoView.layer.add(transition, forKey: nil)

memoView.addSubview(countChartView)

memoView.addSubview(closeMemoButton)

case 2.

UIView.transition(with: self.memoView, duration: 1.0, options: [.transitionFlipFromRight], animations: {

      memoView.addSubview(countChartView)

//       self.memoView.removeFromSuperview()

}, completion: nil)

 

 

반응형

'Programming > Swift' 카테고리의 다른 글

[Swift5] 문자열에 대한 라인수 구하기  (0) 2020.01.29
xcode git 연동 문제  (0) 2020.01.16
[cocoaPods] 프로젝트 만들어 보기  (0) 2019.10.22
[iOS13] 당황스럽게 변경된 점  (0) 2019.10.22
[Swift] opacity  (0) 2019.03.22
반응형

본 내용은 2019년 2월 28일에 메모장에 작성된 것을 복붙한 것이다.

기억이 잘 안나지만, 이게 작동이 되었는지는 알 수 없다.

다만 했다는 기억만으로 이렇게 남겨 놓는다.

 

 

1. Github repository 만들기

 

2. cocoaPods 사이트에서 동일한 이름이 있는지 확인하자.

    ex. https://cocoapods.org/pods/mySamplePods 접속하던가, 사이트내에서 검색을 해보아라.

 

3. cocoaPods 프로젝트 만들기

$ pod lib create demoPods

/Users/sk/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/cocoapods-1.6.1/lib/cocoapods/executable.rb:89: warning: Insecure world writable dir /Users/sk/Documents/2016/hadoop/hadoop-1.2.1/sbin in PATH, mode 040777

Cloning `https://github.com/CocoaPods/pod-template.git` into `demoPods`.

Configuring demoPods template.

/Users/sk/Documents/2016/Development/cocoaPods/demoPods/setup/TemplateConfigurator.rb:207: warning: Insecure world writable dir /Users/sk/Documents/2016/hadoop/hadoop-1.2.1/sbin in PATH, mode 040777

security: SecKeychainSearchCopyNext: The specified item could not be found in the keychain.

 

-----------------------------------------------------------------------------------------------------------------------------

 

To get you started we need to ask a few questions, this should only take a minute.

 

If this is your first time we recommend running through with the guide: 

 - https://guides.cocoapods.org/making/using-pod-lib-create.html

 ( hold cmd and double click links to open in a browser. )

 

 

What platform do you want to use?? [ iOS / macOS ]

 > iOS

 

What language do you want to use?? [ Swift / ObjC ]

 > Swift

 

Would you like to include a demo application with your library? [ Yes / No ]

 > Yes

 

Which testing frameworks will you use? [ Quick / None ]

 > None

 

Would you like to do view based testing? [ Yes / No ]

 > No

security: SecKeychainSearchCopyNext: The specified item could not be found in the keychain.

security: SecKeychainSearchCopyNext: The specified item could not be found in the keychain.

security: SecKeychainSearchCopyNext: The specified item could not be found in the keychain.

security: SecKeychainSearchCopyNext: The specified item could not be found in the keychain.

security: SecKeychainSearchCopyNext: The specified item could not be found in the keychain.

security: SecKeychainSearchCopyNext: The specified item could not be found in the keychain.

 

Running pod install on your new library.

 

/Users/sk/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/cocoapods-1.6.1/lib/cocoapods/executable.rb:89: warning: Insecure world writable dir /Users/sk/Documents/2016/hadoop/hadoop-1.2.1/sbin in PATH, mode 040777

Analyzing dependencies

Fetching podspec for `demoPods` from `../`

Downloading dependencies

Installing demoPods (0.1.0)

Generating Pods project

Integrating client project

 

[!] Please close any current Xcode sessions and use `demoPods.xcworkspace` for this project from now on.

Sending stats

Pod installation complete! There is 1 dependency from the Podfile and 1 total pod installed.

 

[!] Automatically assigning platform `ios` with version `9.3` on target `demoPods_Example` because no platform was specified. Please specify a platform for this target in your Podfile. See `https://guides.cocoapods.org/syntax/podfile.html#platform`.

 

 Ace! you're ready to go!

 We will start you off by opening your project in Xcode

  open 'demoPods/Example/demoPods.xcworkspace'

 

To learn more about the template see `https://github.com/CocoaPods/pod-template.git`.

To learn more about creating a new pod, see `http://guides.cocoapods.org/making/making-a-cocoapod`. 

 - 위 keycahin 찾을수없다는 메세지가 나오는데 모르겠음. 

 - 명령어를 실행시킨 위치에서 하위 폴더가 생성 것이다.

 - Xcode 자동 실행된다.

 

4. mySamplePods.podspec 수정

 - 수정할 대상은 s.name, s.version, s.homepage 등이 있다.
 - 하지만 주어진 포맷대로 수정을 해보았지만 오류가 많다.
 - 나의 방법은 그동안 평소 쓰던 다른 사람들이 만들어 놓은 cocoapods GitHub 라이브러리 들어가서 podspec 파일을 가져와서 그대로 수정해주면 된다.

 

5. 파일을 생성하고 스위프트 버전을 넣어준다.

$ vi .swift-version

4.2 <- 버전

6. pod lib lint

 - .podspec 파일을 맞게 작성했는지 체크를 한다.

 

7. Error 체크

 - 에러가 것이다. 여러가지 에러가 나온다. 정말 울화가 치밀어 오른다. 너무 많은 에러를 접했는데 그나마 자주 등장하는 에러만 적어 보았다.

## 1 ##

WARN  | [iOS] swift: The validator used Swift 3.2 by default because no Swift version was specified. To specify a Swift version during validation, add the `swift_version` attribute in your podspec. Note that usage of the `--swift-version` parameter or a `.swift-version` file is now deprecated.
.swift-version 파일을 생성하였지만, 그래도 위와 같은 에러가 발생한다. 이유모름
“pod lib lint —swift-version=4.2” 같이 실행하라.
—swift-version=4.2 옵션은 아래에서도 동일하게 사용된다.

 

## 2 ##
ERROR | [iOS] file patterns: The `resources` pattern did not match any file.
resources 폴더 또는 파일이 존재않는 것이다. 혹은 경로를 잘못 입력하였거나

 

## 3 ##
WARN  | url: The URL (https://github.com/Name/mySamplePods) is not reachable.
유효한 웹페이지를 입력해야한다. 일단 접속되는 아무 URL 입력해도 되는 같음.

 

## 4 ##
demoPods passed validation.
문구가 나오면 성공한 것이다.

 

8. git push

## $ git init  => 존재한다고 하면 그냥 무시.
Reinitialized existing Git repository in /cocoaPods/mySamplePods/.git/


## $ git add -all
## $ git commit -m “Initial commit”
## $ git tag 0.1.0 => 동일 버전을 입력
## $ git remote add origin https://github.com/developer/mySamplePods.git

## $ git push -u origin master —tags => 에러!! ~ 짱나
error: failed to push some refs to 'https://github.com/developer/mySamplePods.git'
=> 이럴 경우 찾아보니 해결 방법은 많은 같더라. 한개 해봤는데 안돼!
## $ git pull --rebase origin master
## $ git push origin master
=> 강제적으로 넣는게 있다고 해서 그냥 이걸로 했음. $ git push origin +master
## github 사이트에가서 제대로 업로드가 되었는지 확인 해보자. 

 

9. CocoaPods 등록 : 인증작업

$ pod trunk register myEamilAddress@gmail.com mySamplePodsTrunk --description=“mySamplePods.PG"

명령어가 실행이 된 후 메일 내용 확인

 

위 메일 내용의 링크를 클릭하면 이와 같은 페이지가 나타난다.

 

10. CocoaPods 등록 : 업로드

$ pod trunk push demoPods.podspec --swift-version=4.2

에러가 나서 확인을 했더니, .podspec 파일의 값이 리셋되어 있는 것이 아닌가 ㅠㅠ
다시 수정하여 재실행 하였다. 결국에는 아래와 같이 나왔다. 성공이다.

수정이 되었는지 알수없다. 다만 git push 할때 강제로 해서 그럴 같다는 생각이 든다.
https://cocoapods.org/pods/mySamplePods 접속을 해보면 접속이된다.

그러나 이 작업이 성공하지 못하면, 잘못된 페이지라고 나올 것이다.

완료된 메세지

11. 이제 사용 해볼까?

현재버전

Xcode 보면 Pods 프로젝트에서 Development Pods 에서 작업을 하면 되는 같다.
Development Pods > mySamplePods > Pod > Classes > *.swift  —> Classes 없으면 만들어 주면 된다.
수정을 했다고 가정하고, .podspec 파일 버전업을 시켜준다.

그리고 위에서 했던 처럼 git 올리고 cocoapods 올리면 된다.
cocoapods 사이트가서 확인해보면 버전이 올라간 것을 확인 있다.

 

버전업

12. 테스트로 임시적으로 프로젝트를 만들어서 pod install 해보자.

반응형

'Programming > Swift' 카테고리의 다른 글

xcode git 연동 문제  (0) 2020.01.16
[swift] slide animation  (0) 2019.11.21
[iOS13] 당황스럽게 변경된 점  (0) 2019.10.22
[Swift] opacity  (0) 2019.03.22
[Swift] UserDefaults.standard int형식으로 불러오기  (0) 2019.02.18
반응형

1. present(_:animated:completion:)

화면전환 시 사용되는 present의 기존 iOS13 이전까지만 해도 default가 fullScreen 이였다.

하지만 iOS13 부터 formsheet가 되었다. 설정을 위해서는 automatic으로 지정해야한다.

그래서 기존 처럼 fullScreen 을 하기 위해서는 아래와 같이 지정한다.

cell.modalPresentationStyle = .fullScreen

self.present(cell, animated: true, completion: nil)

//자세한 내용

https://zeddios.tistory.com/828

https://stackoverflow.com/questions/56435510/presenting-modal-in-ios-13-fullscreen

https://zonneveld.dev/ios-13-viewcontroller-presentation-style-modalpresentationstyle/

 

2. adMob 전면 광고

잘 되던 전면광고가 formSheet처럼 보여지게 되었고, 광고가 전부 보여지지 않고, 반쪽만 보여지게 되었다.

Google-Mobile-Ads-SDK 를 최신버전으로 설치하자.

필자 같은 경우 7.3 버전이였고 7.5로 업데이트를 하였더니, 아무문제 없었다.

 

2-1. adMob 광고

info.Plist에 이것도 추가를 해줘야한다. 앱이 실행되자마자 크래쉬가 된다.

# Error

Google Ad Manager publishers, follow instructions here: https://googlemobileadssdk.page.link/ad-manager-ios-update-plist

위 문구를 찾아보았다.

//https://stackoverflow.com/questions/55577811/xcode-error-when-added-admob-plugin-to-ionic-project

 

info.Plist 에 GADIsAdManagerApp 를 추가하고 Boolean 값으로 YES로 설정해주면 된다.

 

반응형
반응형

UIView를 반투명하려면 opacity를 사용한다.

let background = UIView()

background.layer.backgroundColor = UIColor.black.cgColor

background.layer.opacity = 0.5 


하지만 이 뷰안에 다른 레이블이 포함되었을 경우, 포함된 레이블도 같이 투명하게 되는 경우가 있다.

let background = UIView()

background.layer.backgroundColor = UIColor.black.cgColor

background.layer.opacity = 0.5

let title = UILabel()

backgroud.addSubview(title)


이럴 경우 이렇게 해보자

let background = UIView()

background.layer.backgroundColor = (UIColor.black.cgColor).copy(alpha: 0.5)

let title = UILabel()

background.addSubview(title)


반응형
반응형

        // 저장할때는 동일하다.

        UserDefaults.standard.set(5, forKey:"num")

        

        // 불러올 때

        UserDefaults.standard.integer(forKey: "num")


반응형
반응형

        let taskText = "All Tasks (task)"

        let attributed = NSMutableAttributedString(string: taskText)

        let strokeTextAttributes = [

//            NSAttributedString.Key.strokeColor : UIColor.black,

            NSAttributedString.Key.foregroundColor : UIColor.black,

//            NSAttributedString.Key.strokeWidth : 2.0,

            NSAttributedString.Key.font : UIFont.boldSystemFont(ofSize: 18)

            ] as [NSAttributedString.Key : Any]

        

        attributed.addAttributes(strokeTextAttributes, range: (taskText as NSString).range(of: "(task)"))

        titleLabel.attributedText = attributed



반응형
반응형

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

        // Override point for customization after application launch.

        UINavigationBar.appearance().barTintColor = UIColor.white//.init(red: 23.0/255, green: 197.0/255, blue: 157.0/255, alpha: 1.0)

        

        // To change colour of tappable items.

        UINavigationBar.appearance().tintColor = .black

        

        // To apply textAttributes to title i.e. colour, font etc.

        UINavigationBar.appearance().titleTextAttributes = [.foregroundColor : UIColor.black, .font : UIFont.init(name: "AvenirNext-DemiBold", size: 22.0)!]

        

        // To control navigation bar's translucency.

        UINavigationBar.appearance().isTranslucent = false


        return true

    }


반응형
반응형

override func viewDidLoad() {

        super.viewDidLoad()

        self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: UIBarMetrics.default)

        self.navigationController?.navigationBar.shadowImage = UIImage()

}


반응형
반응형

사실 이게 무엇인지 모른다.

다만 추측하건데, 이미지의 색상을 지원하는 포맷이랄까?

RGB 또는 256 컬러 이런게 업그레이드 되어 색상을 얼마나 지원줄 수있는지의 설정값 같다.



1. 어떻게 알았는가?


collectinView 에 저장된 이미지를 보여주기 위해 구현 하였다.

ipad 시뮬레이터에서만 이미지가 부분적으로 보여지고 있었다.

iphone 에서는 잘되는 것이 pad 에서만 안되고 있으니, 미치고 팔짝 뛸 노릇이였다.


보여지는 이미지와 보여지지 않는 이미지를 비교를 해보았다.

Xcode에서 아래와 같이 보여졌다.


- 보여지는 이미지


- 보여지지 않는 이미지



위 두 개의 이미지를 비교했을 때  Color Space가 유독 눈에 들어온다.

sRGB  와 Apple Wide Color

Apple Wide Color는 무엇인가? ㅠㅠ

아무튼 해결 방법은 Apple Wide Color를 sRGB로 바꿔주면 되는 거 아닌가



2.해결

1.기본 사진 어플리케이션에 이미지를 넣어준다.

2.해당 이미지를 선택하고 command + shift + E 를 누르면 아래와 같이 나온다.



3. 색상프로파일을 선택하고, sRGB로 선택하고 내보내기를 누르면 바뀐형식의 이미지 파일 생성된다.

4. 생성된 파일을 올리고 컴파일을 해보면 정상적으로 작동된다.



3.결론

그리고 왠지 모르게 sRGB보다 apple wide color 가 더 색을 많이 지원해 줄 것 같다는 생각이들었다.

그런데 apple wide color 인데 apple꺼인 xcode에서 지원이 안된다는 것은 좀 이상하지 않은가


구글링을 해본 결과, xcode 버그 일것 같다는 의견들이 많았다.

나도 그냥 이렇게 생각하고 싶다.

반응형
반응형


키보드가 활성화 될 때 하단 부분은 가려지게 될 것이다.

반드시 보여져야 하는 레이어들이라면 키보드 위로 올려서 보여질 수 있게 해보자.

let inputTyping = UITextView()

let buttonExecution = UIButton()

override func viewDidLoad() {

    super.viewDidLoad()

    let tap:UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.dismissKeyboard))

    self.view.addGestureRecognizer(tap)

    NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)

    NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)

}

@objc func dismissKeyboard() {

    self.view.endEditing(true)

}

@objc func keyboardShow(notification: NSNotification) {

        if let keyboardSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {

            if self.view.frame.origin.y == 0 {

                self.view.frame.origin.y -= keyboardSize.height

                self. inputTyping.frame.origin.y -= keyboardSize.height

                self. buttonExecution.frame.origin.y -= keyboardSize.height

        }

    }

}

@objc func keyboardHide(notification: NSNotification) {

    if let keyboardSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {

        if self.view.frame.origin.y != 0 {

            self.view.frame.origin.y += keyboardSize.height

             self. inputTyping.frame.origin.y += keyboardSize.height

            self. buttonExecution.frame.origin.y += keyboardSize.height

        }

    }



나의 삽질은 어디까지 인 것인가?


화면의 반을 차지하는 imageView, 그 아래 textView, 그 아래 button 이 위치하도록 구현을 하였다.

여기서 내가 원하던 것은 키보드가 활성화 될 때 일부로 버튼이 보여지지 않게 하고 imageView 와 textView 창만 올라가게 끔 하려고 했다.

물론 위 소스와 동일하게 했을 시 잘 올라간다.

여기서 더 욕심을 내서 textView를 키보드 바로 위로 맞춰서 하는게 나의 목표였다.

이해가 되질 않는다면 아래 그림을 보면 될 것이다.



그런데....

키보드 바로 위로 textView를 맞춰지지 않는 것이다.

키보드에 가려져 보이지 않거나, 반만 보이거나, 너무 위로 올라가서 키보드와의 간격이 넓어지거나

온갖(?) 방법을 다 해보았다.

온갖 방법이란 내 머리속의 수학 아닌 산수를 동원하여, 위치값까지 하나하나 찾아가고,

"일단 키보드가 바라보는 디바이스의 위치값과 뷰안에 존재하는 위치값은 다를 수 있지!!" 라며

말이 되는 가설과 말도 안되는 가정들을 노트에 수십번을 적어가며

계산하고 계산하였다.


이렇게 구구절절 얘기하는 것은 그만큼 삽질을 많이 했다는 얘기이다.

결국에는 내가 세운 계산법으로는 해내지 못하였다.


포기하고 버튼도 위로 올려버렸다.

위 소스에서 한줄만 더 추가하면 된다.

소스의 파란색 글씨가 그것이다.

1. keyboardShow => self. buttonExecution.frame.origin.y -= keyboardSize.height

2. keyboardHide => self. buttonExecution.frame.origin.y += keyboardSize.height  


허무하게 이 한줄을 넣고 시뮬레이션을 돌리는 순간.

유레카!!!!


이 한줄 추가하면서 모든게 제대로 잘 보여지는데,

아래 버튼 사이즈만 내려볼까?

라는 생각이 들어버렸다.


되면 당연히 좋지만, 한편으로는 엄청 허무할 것 같다는 생각이 들었다.

성공

@objc func keyboardShow(notification: NSNotification) {

        if let keyboardSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {

            let keyboardResize = keyboardSize.height - createButton.frame.height

            if self.view.frame.origin.y == 0 {

                self.view.frame.origin.y -= keyboardResize

                self. textView.frame.origin.y -= keyboardResize

        }

    }

}


성공은 했지만, 버튼을 위로 올리는 것이 나을 것 같아서 적용은 하지 않았다.

추후에 적용할 일이 생기면 참고하기 위해서 이렇게 글로 남겨 놓는다.

매번 느끼는 것이지만 항상 허무한 결론이다.


참고 URL

https://stackoverflow.com/questions/26070242/move-view-with-keyboard-using-swift


반응형
반응형

1. 이미지 사이즈

https://developer.apple.com/ios/human-interface-guidelines/icons-and-images/custom-icons/

필자는 25사이즈로 한다.

참고로 이미지는 png 확장자를 사용하며, 투명바탕에 흰색 이미지를 사용하는 것이 좋은 것 같다.


2. 탭바 선택하였을 때 이미지가 변화되도록 하려면



반응형
반응형

시뮬레이터를 하는 아래와 같은 메세지로 인해 다운이 되었다.


libsystem_kernel.dylib`__abort_with_payload: 


내가 사용할 것은 UIImagePicker이다.

엄청 난 삽질 끝에 알아낸 사실은 Info.plist에 추가해 줘야한다는 것을 깜빡 잊고 있었다.

Privacy - Photo Library Usage Description 


반응형
반응형

import UIKit


var totalCount = 18

var gemCard = 1

var ranArray = [1,2,3,4,5,6,7,8,9,10,11,12,13]


while(totalCount>0) {

    

    let randomIndex = Int(arc4random_uniform(UInt32(ranArray.count)))

    print(ranArray[randomIndex])

    

    ranArray.remove(at: randomIndex)

    

    totalCount-=2

} 


반응형
반응형

https://www.youtube.com/watch?v=dqad3XuMwHI


1. 해당 음악 파일을 추가하였을 경우 Build Phases 에 추가가 되었는지 확인해 보자. (ex. sample.mp3)

   추가가 안되어있으면 + 버튼으로 추가해 주면 된다.


2. 어플이 종료 되어도 백그라운드에서 돌아갈 수 있게 하려면 아래와 같이 설정 해야 한다.


3. 소스

import UIKit

import AVFoundation


class ViewController: UIViewController {


    var audioPlayer = AVAudioPlayer()

    

    override func viewDidLoad() {

        super.viewDidLoad()

        // Do any additional setup after loading the view, typically from a nib.

        do {

            audioPlayer = try AVAudioPlayer(contentsOf: URL.init(fileURLWithPath: Bundle.main.path(forResource: "sample", ofType: "mp3")!))

            audioPlayer.prepareToPlay()

            

            // 백그라운드에서도 돌아갈 수 있게 하는 코드

            var audioSession = AVAudioSession.sharedInstance()

            do {

                try audioSession.setCategory(AVAudioSessionCategoryPlayback)

            } catch {

                

            }

            

        } catch {

            print(error)

        }

    }


    override func didReceiveMemoryWarning() {

        super.didReceiveMemoryWarning()

        // Dispose of any resources that can be recreated.

    }

    

    @IBAction func play(_ sender: Any) {

        audioPlayer.play()

        

    }


    @IBAction func pause(_ sender: Any) {

        if audioPlayer.isPlaying {

            audioPlayer.pause()

        } else {

            

        }

    }

    

    @IBAction func restart(_ sender: Any) {

        if audioPlayer.isPlaying {

            audioPlayer.currentTime = 0

            audioPlayer.play()

        } else {

            audioPlayer.play()

        }

        

    }

} 


4. 시뮬레이터를 돌렸을 경우 백그라운드 설정을 굳이 안해도, 어플이 종료가 되어도 음악이 나왔다.

   그러나 아이폰에 직접 넣어서 해보았더니, 백그라운드 설정해야지 되더라!

반응형
반응형
반응형
반응형

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

    let width = collectionView.frame.width / 4 - 1

    return CGSize(width: width, height: width)

}

 

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {

    return 1.0

}

    

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {

    return 1.0


반응형

'Programming > Swift' 카테고리의 다른 글

[AVPlayer] background audio  (0) 2017.09.11
ttf, otf 폰트 추가하는 법  (0) 2017.09.09
UIImageView 를 다른 UIImageView로 동일한 크기로 처리  (0) 2017.08.21
[ERROR] csqlite, stdatomic.h  (0) 2017.05.18
background to foreground  (0) 2017.04.27
반응형

var TempImageView: UIImageView? = nil

var img: UIImageView? = nil


img.image = UIImage(data: "aaaa.png");


if let MainSize = TempImageView?.frame.size {

    img.frame.size = MainSize

    TempImageView?.contentMode = UIViewContentMode.scaleAspectFill

    TempImageView?.clipsToBounds = true


    TempImageView?.addSubview(img)

} 

생각나는 대로 작성을 하였기 때문에 작동은 안될 것 같다.

다만 위와 비슷하게 작업으로 한다면 처리 될 것이다.


반응형

'Programming > Swift' 카테고리의 다른 글

ttf, otf 폰트 추가하는 법  (0) 2017.09.09
[Swift] CollectionView Layout 비율 맞추기  (0) 2017.09.04
[ERROR] csqlite, stdatomic.h  (0) 2017.05.18
background to foreground  (0) 2017.04.27
버튼을 통한 Boolean  (0) 2017.04.17
반응형

Xcode7 과 Xcode8 버전으로 작업을 하고 있다.

응용프로그램에 디폴트 Xcode를 8로 하고 Xcode 7을 다른 폴더에 넣어 두었다.


나의 소스의 차이점

Xcode7 

Xcode8 

SQLite Manual 사용 

SQLite CocoPods 사용 


그러나 Xcode7 에서 구버전 소스를 컴파일을 하려고 하였으나, 아래와 같은 에러가 메세지가 나왔다.

could not build objective-c module 'csqlite'

header 'stdatomic.h' not found  


기존에는 되었던 것이고, 소스 변경도 없었는데, 도저히 원인이 파악이 되지 않았다.

SQLite 도 Manual로 하였기에 소스도 예전 소스이다.


이것은 이렇게 하니, 해결 하였다.


응용프로그램 디폴트 Xcode를 7로 해보니 되더라


아무래도 Xcode와 연결된 모듈(lib파일등등) 들이 "Xcode"로 설정되어 있어서 그런 것 같다는.......그냥 나의 생각!


반응형
반응형

    override func viewDidLoad() {

        super.viewDidLoad()

        NotificationCenter.default.addObserver(self, selector: #selector(willEnterForeground), name: .UIApplicationWillEnterForeground, object: nil)

    }

    

    func willEnterForeground() {

        // do stuff

        print("complete TEST")

        

    } 


반응형
반응형

동일한 버튼을 클릭할 때마다 boolean 값을 바꿔주는 경우가 종종 있다.

이런 경우 아래와 같이 했었다.

var buttonValue = false

@IBAction func BoolButton(_ sender: UIButton) {

    if buttonValue == true {

        buttonValue = false

    } else {

        buttonValue = true

    }

}


이것을 단순하게 바꿔본다면...

var buttonValue = false

@IBAction func BoolButton(_ sender: UIButton) {

    buttonValue = !buttonValue


끝!

반응형

'Programming > Swift' 카테고리의 다른 글

[ERROR] csqlite, stdatomic.h  (0) 2017.05.18
background to foreground  (0) 2017.04.27
xcode에서 시뮬레이터가 보이지 않을 때  (0) 2017.03.10
swift3.0 설정으로 가기  (0) 2017.02.17
alertMessage 왼쪽 정렬  (0) 2017.02.15
반응형


xcode 상단에 보면 종류별로 아이폰을 시뮬레이터를 할 수 있는 리스트가 나와 있다.

그러나 보이지 않을 경우가 있다.



이렇게 하면 해결 된다.


1. 어플명을 클릭하면 아래와 같이 메뉴가 나오고, Edit Scheme를 선택한다.



2. "Run" 의 Executable을 보면 None으로 되어 있을 것이다. 이부분을 선택하여, 해당 어플명을 골라주면 끝이다.



반응형

'Programming > Swift' 카테고리의 다른 글

background to foreground  (0) 2017.04.27
버튼을 통한 Boolean  (0) 2017.04.17
swift3.0 설정으로 가기  (0) 2017.02.17
alertMessage 왼쪽 정렬  (0) 2017.02.15
3D 터치 구현  (0) 2017.02.02
반응형

http://stackoverflow.com/questions/28152526/how-do-i-open-phone-settings-when-a-button-is-clicked-ios


  • prefs:root=General&path=About
  • prefs:root=General&path=ACCESSIBILITY
  • prefs:root=AIRPLANE_MODE
  • prefs:root=General&path=AUTOLOCK
  • prefs:root=General&path=USAGE/CELLULAR_USAGE
  • prefs:root=Brightness
  • prefs:root=Bluetooth
  • prefs:root=General&path=DATE_AND_TIME
  • prefs:root=FACETIME
  • prefs:root=General
  • prefs:root=General&path=Keyboard
  • prefs:root=CASTLE
  • prefs:root=CASTLE&path=STORAGE_AND_BACKUP
  • prefs:root=General&path=INTERNATIONAL
  • prefs:root=LOCATION_SERVICES
  • prefs:root=ACCOUNT_SETTINGS
  • prefs:root=MUSIC
  • prefs:root=MUSIC&path=EQ
  • prefs:root=MUSIC&path=VolumeLimit
  • prefs:root=General&path=Network
  • prefs:root=NIKE_PLUS_IPOD
  • prefs:root=NOTES
  • prefs:root=NOTIFICATIONS_ID
  • prefs:root=Phone
  • prefs:root=Photos
  • prefs:root=General&path=ManagedConfigurationList
  • prefs:root=General&path=Reset
  • prefs:root=Sounds&path=Ringtone
  • prefs:root=Safari
  • prefs:root=General&path=Assistant
  • prefs:root=Sounds
  • prefs:root=General&path=SOFTWARE_UPDATE_LINK
  • prefs:root=STORE
  • prefs:root=TWITTER
  • prefs:root=FACEBOOK
  • prefs:root=General&path=USAGE prefs:root=VIDEO
  • prefs:root=General&path=Network/VPN
  • prefs:root=Wallpaper
  • prefs:root=WIFI
  • prefs:root=INTERNET_TETHERING
  • prefs:root=Phone&path=Blocked
  • prefs:root=DO_NOT_DISTURB


let settingsUrl = URL(string: "App-Prefs:root=General&path=Keyboard")

if let url = settingsUrl {

    UIApplication.shared.open(url, options: [:], completionHandler: nil)

} 


반응형

'Programming > Swift' 카테고리의 다른 글

버튼을 통한 Boolean  (0) 2017.04.17
xcode에서 시뮬레이터가 보이지 않을 때  (0) 2017.03.10
alertMessage 왼쪽 정렬  (0) 2017.02.15
3D 터치 구현  (0) 2017.02.02
Notification - FCM 설정(3) : 소스 및 테스트  (0) 2017.02.02
반응형
 - 변경 전

let alertController = UIAlertController(title: "삭제 하시겠습니까?", message: "사용자: \(username)"+"\n"+"휴대폰: \(phone)"+"\n"+"네이트온: \(nateon)", preferredStyle: .alert)

            

let submit = UIAlertAction(title: "Submit", style: UIAlertActionStyle.default, handler: { (paramAction:UIAlertAction) in

    if let status = self.ArrayUserName[indexPath.row].authstatus, let auth = self.ArrayUserName[indexPath.row].authvalue {

        self.ProcessData(flag: "delete", authvalue: auth, authstatus: status)

    }

        self.ArrayUserName.remove(at: indexPath.row)

        tableView.deleteRows(at: [indexPath], with: UITableViewRowAnimation.automatic)

    })


    let cancel = UIAlertAction(title:"Cancel", style:UIAlertActionStyle.cancel, handler:nil)

            

    alertController.addAction(submit)

    alertController.addAction(cancel)

    self.present(alertController, animated: true, completion: nil)



 - 변경 후

let userMessage = "사용자: \(username)"+"\n"+"휴대폰: \(phone)"+"\n"+"네이트온: \(nateon)"

let alertController = UIAlertController(title: "삭제 하시겠습니까?", message: userMessage, preferredStyle: .alert)

            

let submit = UIAlertAction(title: "Submit", style: UIAlertActionStyle.default, handler: { (paramAction:UIAlertAction) in

    if let status = self.ArrayUserName[indexPath.row].authstatus, let auth = self.ArrayUserName[indexPath.row].authvalue {

        self.ProcessData(flag: "delete", authvalue: auth, authstatus: status)

    }

                

        self.ArrayUserName.remove(at: indexPath.row)

         tableView.deleteRows(at: [indexPath], with: UITableViewRowAnimation.automatic)

     })

    let cancel = UIAlertAction(title:"Cancel", style:UIAlertActionStyle.cancel, handler:nil)

            

    let paragraphStyle = NSMutableParagraphStyle()

    paragraphStyle.alignment = NSTextAlignment.left

            

    let messageText = NSMutableAttributedString(

        string: userMessage,

        attributes: [

            NSParagraphStyleAttributeName: paragraphStyle,

            NSFontAttributeName: UIFont.systemFont(ofSize: 15.0)

         ]

    )

    alertController.setValue(messageText, forKey: "attributedMessage")        

    alertController.addAction(submit)

    alertController.addAction(cancel)

    self.present(alertController, animated: true, completion: nil) 


반응형
반응형

아래 유튜브 동영상을 보고 그대로 따라한 것을 내 나름대로 정리해 보았다.

https://www.youtube.com/watch?v=NO9E5KxixOw



위 그림으로 보자면,

테이블뷰 메인화면을 만들고 해당 셀을 클릭 했을 경우, 일반적으로 AddStuffViewController로 넘어가게 된다.

여기서 해당 셀을 클릭하지 않고, 강하게 누르고 있을 경우, 즉 3D터치를 하였을 경우 PreviewViewController로 보여지게 끔 하려는 것이 목적이다.


아래 소스의 색이 칠해져 있는 것은 3d터치와 연관된 소스이니, 이부분만 참고하면 될 듯 싶다.


 - MasterViewController.swift

import UIKit


class MasterViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    


    @IBOutlet weak var MenuTable: UITableView?

    var data = ["Awesome Stuff","Interesting Stuff","Cool Stuff"]

    

    var stuffType:String? = nil

    var quickActionString:String? = nil

    

    override func viewDidLoad() {

        super.viewDidLoad()

        // Do any additional setup after loading the view, typically from a nib.

        

        

        MenuTable?.delegate = self

        MenuTable?.dataSource = self

        

        if traitCollection.forceTouchCapability == .available {

            registerForPreviewing(with: self, sourceView: MenuTable!)

        }

    }


    override func didReceiveMemoryWarning() {

        super.didReceiveMemoryWarning()

        // Dispose of any resources that can be recreated.

    }


    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return data.count

    }

    

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        

        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)

        cell.textLabel?.text = data[indexPath.row]

        

        return cell

    }

    

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        if let cell = MenuTable?.cellForRow(at: indexPath) {

            stuffType = cell.textLabel?.text

            self.performSegue(withIdentifier: "showStuff", sender: self)

        }

    }

    

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

        if segue.identifier == "showStuff" {

            let stuffVC = segue.destination as? AddStuffViewController

            stuffVC?.detailInfo = stuffType

        }

    }


} 


 - MasterViewController+UIViewControllerPreviewing.swift

   : 확장 클래스로 이 부분이 핵심이다.

import UIKit


extension MasterViewController: UIViewControllerPreviewingDelegate {


    // PEEK

    func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? {

        

        guard let indexPath = MenuTable?.indexPathForRow(at: location),

            let cell = MenuTable?.cellForRow(at: indexPath) else {return nil}

        

        

        guard let previewVC = storyboard?.instantiateViewController(withIdentifier: "PreviewVC") as? PreviewViewController else {return nil}

        

        previewVC.selectedItem = data[indexPath.row]

        quickActionString = data[indexPath.row]

        

        previewVC.preferredContentSize = CGSize(width: 0, height: 150)

        

        previewingContext.sourceRect = cell.frame

        

        return previewVC

    }

    

    // POP

    func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) {

        if let stuffVC = storyboard?.instantiateViewController(withIdentifier: "AddStuffVC") as? AddStuffViewController {

            stuffVC.detailInfo = quickActionString

            

            show(stuffVC, sender: self)

        }

    }

} 


 - PreviewViewController.swift

    : 3D 터치가 작동되었을 시 보여주는 형식이다.

    : 3D 터치 작동 중 화면을 위로 올렸을 경우, "Do something" 과 "Do even more " 메뉴가 나타나게 된다.

import UIKit


class PreviewViewController: UIViewController {


    var selectedItem: String? = nil

    var previewActions:[UIPreviewActionItem] {

        let item1 = UIPreviewAction(title: "Do something", style: .default) { (action:UIPreviewAction, vc:UIViewController) -> Void in

            print("Awesome")

        }

        

        let item2 = UIPreviewAction(title: "Do even more", style: .default) { (action:UIPreviewAction, vc:UIViewController) -> Void in

            print("cool")

        }

        

        return [item1,item2]

    }

    

    @IBOutlet weak var previewLabel: UILabel?

    

    override func viewDidLoad() {

        super.viewDidLoad()


        // Do any additional setup after loading the view.

    }


    override func viewWillAppear(_ animated: Bool) {

        super.viewWillAppear(animated)

        previewLabel?.text = selectedItem

    }

    

    override func didReceiveMemoryWarning() {

        super.didReceiveMemoryWarning()

        // Dispose of any resources that can be recreated.

    }

} 


 - AddStruffViewController.swift

    : 일반적인 테이블뷰 값을 보여주는 것이라 본 내용과는 크게 중요하지 않다.



 - 3D 터치 프로젝트 파일

ThreeTouch.zip

반응형

+ Recent posts